2 Commentss
  • 0

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/post.php

Line Number: 190


File: /home2/naijacod/public_html/application/views/post.php
Line: 190
Function: _error_handler

File: /home2/naijacod/public_html/application/controllers/Posts.php
Line: 420
Function: view

File: /home2/naijacod/public_html/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Safe Guard in Javascript

Hi everyone... I am pretty sure almost everyone here is solid on Javascript so I will be going straight to the point...

If you have an Object that keys are not constant, like they change based on conditions... or from API request...

Code Example:


const obj = {};

const isString = true

if (isString) obj.value = "it's a string";

else obj.error = "it's not a string"


The above example is always going to be true because he hard coded it but let's assume it will evaluate to either true or false based on input. 

Now let's say you want to access the value key in the object and trim all whitespaces... you can't assume value will be there because it might evaluate to false... So it is not advisable to assume.

Code Example:


// you can't do this... you can though but don't 



If the condition evaluate to false, there won't be value key in the object and the above will crash your app because it can't read undefined which is what the above will evaluate to.

So the best approach around this is to safeguard it... 

Code example:


// you need to be sure that the key is there

obj.value && obj.value.trim()

// the above will not break because it will only run if obj.value is true...

// you can also do it like this but we are sure the obj variable exist because we hard coded it or typed it ourselves

obj && obj.value && obj.value.trim()


This is how to safeguard or check a key exist before running your program to avoid unexpected breaking...