Modifying Jquery's val() method but not working properly - javascript

So i tried to modified the original jQuery's val() method using the following code
(function ($) {
var original_val = jQuery.fn.val;
jQuery.fn.val = function( value ) {
var elem = this[0], val = undefined;
// Set for value first, if its undefined
val = value ? value : "";
if (elem){
if (elem.hasAttribute('thisattribute')){
if (val){
if (typeof val === 'number'){
// Do something here if val is a typeof number
}
} else {
// Do something here if val doesn't exist
}
}
}
console.log("Let me see what is value ::: ", val);
console.log("Let me see what is elem ::: ", elem);
return original_val.apply(this, [val]);
}
})(jQuery);
Using the code above, i check if the input element has a certain attribute on it, then proceed with modifying the value, before passing it to the original jQuery's val() method.
Using this method i managed to modify the value when i use the following code
$(id).val(10000)
But when i tried to retrieve the value using bottom code, it failed
$(id).val()
Some more, i can no longer chain the val() method with other method like trim() after i modified it, as it throws me the following error
Uncaught TypeError: input.val(...).trim is not a function
What did i do wrong here?

It's because your code is always providing an argument to the original val when calling it, even when being used as a getter. So the original val always thinks it's being called to set the value.
I'd make the getter case an early exit from the function, right near the top:
if (!arguments.length) {
return original_val.call(this);
}
(That's the same check jQuery does.)
Some side notes:
This:
return original_val.apply(this, [val]);
can be more efficiently written like this:
return original_val.call(this, val);
No need to create that array.
In a couple of places, you're testing for falsiness but the code seems to be meant to check for undefined instead
Live Example, see *** comments:
(function($) {
var original_val = jQuery.fn.val;
jQuery.fn.val = function(value) {
// *** Early exit when used as a getter
if (!arguments.length) {
return original_val.call(this);
}
var elem = this[0],
val = undefined;
// Set for value first, if its undefined
// *** Note: This converts any falsy value to "", not just undefined.
// *** Later you have a check for `val` being a number. `0` is falsy.
val = value ? value : "";
if (elem) {
if (elem.hasAttribute('thisattribute')) {
if (val) { // *** Again, 0 is falsy
if (typeof val === 'number') {
// Do something here if val is a typeof number
}
} else {
// Do something here if val doesn't exist
}
// Just for the purposes of demonstration:
val = val.toUpperCase ? val.toUpperCase() : val;
}
}
console.log("Let me see what is value ::: ", val);
console.log("Let me see what is elem ::: ", elem);
return original_val.call(this, val);
}
})(jQuery);
// *** Setting a value
$("#txt").val("foo");
// *** Reading a value
console.log($("#txt").val());
<input type="text" id="txt" value="" thisattribute="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

Javascript Object returning undefined

I am creating a variable where its value is determined by a particular method. This particular method should return an object with two properties. However, after the method returns the variable is undefined. I check the objects value right before it's returned and its fine. So there is something happening between the return and instantiate of the variable that causes it to be undefined. Here is a code snippet:
var results = findTarget(target, after, append); //undefined
function findTarget(target, after, append){
var currenttemplate = $(target).attr('data-template');
for(var i=0; i<after.length; i++){
if(after[i] === currenttemplate)
return {target : target, drop : "after"};
}
for(var j=0; j<append.length; j++){
if(append[j] === currenttemplate){
var obj = {target : target, drop : "append"};
console.log(obj); //is fine here
return obj; //this gets returned
}
}
if(currenttemplate === threshold) {
return "";
}
findTarget($(target).parent()[0], after, append);
}
You need to add a return at the end:
function findTarget(target, after, append){
/* ... */
return findTarget($(target).parent()[0], after, append);
}
If not, you call recursively findTarget, and this recursive call returns the appropriate value, but the first call to findTarget doesn't return it.

Can I detect if a variable in javascript increases or decreases in value?

I have a a variable, which always is an integer, that increases and/or decreases in value from time to time, goes from 1-5.
I wanted to know if I can, in any way, detect if it goes up or down, for example:
The variable is currently at three, if it increases to four, it runs a function, but if it decreases to two, it runs another function.
Can that be done?
The following four methods will work depending on support by browser compatibility, and this post did take me a while, but it also taught me what ___ does, and I hope I listed most methods, and if you know more, you could post an answer. However, it would be greatful of you to post your method in the comments so I can add it to this answer. Cheers!
1 Use Object.observe:
Object.observe(i, function(b){ b.object[change.name] > b.type ? console.log('decreased') : console.log('increased'); });
Additional notes about Object.observe
If you like to enable it in Chrome 33,
Visit chrome://flags/
And enable Enable Experimental JavaScript
2 Use setInterval:
var i = 4;
var a = i;
setInterval(function()
{
if(i != a) a > i ? console.log('decreased') : console.log('increased');
}, 1000);
i = 10;
should log 'increase' in one second.
3 Use Object.watch:
var i = {i:5};
i.watch("i", function (id, oldval, newval) {
newval > oldval ? console.log('decreased') : console.log('increased');
return newval;
});
Additional notes about Object.watch
To support more browsers, add this script:
if (!Object.prototype.watch) {
Object.defineProperty(Object.prototype, "watch", {
enumerable: false
, configurable: true
, writable: false
, value: function (prop, handler) {
var
oldval = this[prop]
, newval = oldval
, getter = function () {
return newval;
}
, setter = function (val) {
oldval = newval;
return newval = handler.call(this, prop, oldval, val);
}
;
if (delete this[prop]) { // can't watch constants
Object.defineProperty(this, prop, {
get: getter
, set: setter
, enumerable: true
, configurable: true
});
}
}
});
}
// object.unwatch
if (!Object.prototype.unwatch) {
Object.defineProperty(Object.prototype, "unwatch", {
enumerable: false
, configurable: true
, writable: false
, value: function (prop) {
var val = this[prop];
delete this[prop]; // remove accessors
this[prop] = val;
}
});
}
obtained from https://gist.github.com/eligrey/384583
4. Use a custom value set function:
i = 4;
function setValue(obj, val)
{
val < obj ? console.log('decrease') : console.log('increase');
obj = val;
}
setValue(i, 10);
should log 'increase'.
Most of these require the variable to be an Object, so I'd rather detect over time as seen in method 2.
Sure, but you'll have to check it periodically. Since you didn't provide code, I won't, either. :-)
Set a second variable equal to the first
Check the second against the first at regular intervals (or upon some event)
Respond accordingly
As was mentioned in the comments, there are better ways, such as running functionality alongside (or as a callback to) whatever changes the variable's value in the first place.
let prev;
const change = (i) => {
if (prev === undefined) prev = i;
const next = i;
if (prev < next) console.log("increase");
if (prev > next) console.log("decrease");
prev = next;
};
Rather than detecting if a variable changes, I would use a function to modify the variable. That way, the function can then check if the value has changed and call the new function if it has. Something like:
var triggerVariable;
function changeVariable(newVal){
if(triggerVariable !== newVal){
triggerVariable = newVal;
callFunction();
}
}
function callFunction(){
alert('variable changed!');
}
changeVariable(10);
Object.observe is supposed to be well supported. You can track your state as you please (probably in a closure of some sort).
http://updates.html5rocks.com/2012/11/Respond-to-change-with-Object-observe
you can also create a class for this special variable, and write custom functions for mathematical functions with callback. here is an example with the add function
function specVal (value)
{
this.onChange = null;
this.value = value;
this.val = function()
{
return this.value;
};
this.add = function(i)
{
this.value += i;
if (this.onChange != null)
this.onChange(this);
return this;
}
}
function somethingChanged(val)
{
alert('changed: ' + val.val());
}
myValue = new specVal(10);
myValue.onChange = somethingChanged;
myValue.add(5);
myValue.add(4);
I would either use an MV* framework as suggested (knockout is a lightweight option)
or never change the variable directly.
Use a setter function that changes its value and triggers a custom event each time.
JQuery example:
Function setMyVar(val){
if(_myVar !== val){
_myVar = val;
$('#anyelement').triggerHandler('myvarupdated', [myVar]);
}
}
Very similar to prior answers.
Set a second variable equal to the first
Check the second against the first at regular intervals (or upon some event)
Respond accordingly
But organise it differently. And make sure you leave the last variable outside of the function. Moreover, at the end of your if conditional statements update the value for the one being checked for changes.
Hope it helps!
var lastValue = 0;
$(function () {
if (lastValue > originalValue){
console.log ("Increasing");
}
else if (lastValue < originalValue) {
console.log("Decreasing");
}
lastValue = originalValue;
});
Check this JSFiddle

In javascript, how to trigger event when a variable's value is changed? [duplicate]

This question already has answers here:
Listening for variable changes in JavaScript
(29 answers)
Closed 6 years ago.
I have two variables:
var trafficLightIsGreen = false;
var someoneIsRunningTheLight = false;
I would like to trigger an event when the two variables agree with my conditions:
if(trafficLightIsGreen && !someoneIsRunningTheLight){
go();
}
Assuming that those two booleans can change in any moment, how can I trigger my go() method when they change according to the my conditions?
There is no event which is raised when a given value is changed in Javascript. What you can do is provide a set of functions that wrap the specific values and generate events when they are called to modify the values.
function Create(callback) {
var isGreen = false;
var isRunning = false;
return {
getIsGreen : function() { return isGreen; },
setIsGreen : function(p) { isGreen = p; callback(isGreen, isRunning); },
getIsRunning : function() { return isRunning; },
setIsRunning : function(p) { isRunning = p; callback(isGreen, isRunning); }
};
}
Now you could call this function and link the callback to execute go():
var traffic = Create(function(isGreen, isRunning) {
if (isGreen && !isRunning) {
go();
}
});
traffic.setIsGreen(true);
//ex:
/*
var x1 = {currentStatus:undefined};
your need is x1.currentStatus value is change trigger event ?
below the code is use try it.
*/
function statusChange(){
console.log("x1.currentStatus_value_is_changed"+x1.eventCurrentStatus);
};
var x1 = {
eventCurrentStatus:undefined,
get currentStatus(){
return this.eventCurrentStatus;
},
set currentStatus(val){
this.eventCurrentStatus=val;
}
};
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
x1.currentStatus="create"
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
x1.currentStatus="edit"
console.log("eventCurrentStatus = "+ x1.eventCurrentStatus);
console.log("currentStatus = "+ x1.currentStatus);
The most reliable way is to use setters like that:
var trafficLightIsGreen = false;
var someoneIsRunningTheLight = false;
var setTrafficLightIsGreen = function(val){
trafficLightIsGreen = val;
if (trafficLightIsGreen and !someoneIsRunningTheLight){
go();
};
};
var setSomeoneIsRunningTheLight = function(val){
trafficLightIsGreen = val;
if (trafficLightIsGreen and !someoneIsRunningTheLight){
go();
};
};
and then instead of assigning a value to a variable, you just invoke the setter:
setTrafficLightIsGreen(true);
There is no way to do it without polling with setInterval/Timeout.
If you can support Firefox only, you can use https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch
Which will tell you when a property of an object changes.
Your best solution is probably making them part of an object and adding getters, setters that you can send out notifications yourself, as JaredPar showed in his answer
You could always have the variables be part of an object and then use a special function to modify the contents of it. or access them via window.
The following code can be used to fire custom events when values have been changed as long as you use the format changeIndex(myVars, 'variable', 5); as compared to variable = 5;
Example:
function changeIndex(obj, prop, value, orgProp) {
if(typeof prop == 'string') { // Check to see if the prop is a string (first run)
return changeIndex(obj, prop.split('.'), value, prop);
} else if (prop.length === 1 && value !== undefined &&
typeof obj[prop[0]] === typeof value) {
// Check to see if the value of the passed argument matches the type of the current value
// Send custom event that the value has changed
var event = new CustomEvent('valueChanged', {'detail': {
prop : orgProp,
oldValue : obj[prop[0]],
newValue : value
}
});
window.dispatchEvent(event); // Send the custom event to the window
return obj[prop[0]] = value; // Set the value
} else if(value === undefined || typeof obj[prop[0]] !== typeof value) {
return;
} else {
// Recurse through the prop to get the correct property to change
return changeIndex(obj[prop[0]], prop.slice(1), value);
}
};
window.addEventListener('valueChanged', function(e) {
console.log("The value has changed for: " + e.detail.prop);
});
var myVars = {};
myVars.trafficLightIsGreen = false;
myVars.someoneIsRunningTheLight = false;
myVars.driverName = "John";
changeIndex(myVars, 'driverName', "Paul"); // The value has changed for: driverName
changeIndex(myVars, 'trafficLightIsGreen', true); // The value has changed for: traggicIsGreen
changeIndex(myVars, 'trafficLightIsGreen', 'false'); // Error. Doesn't set any value
var carname = "Pontiac";
var carNumber = 4;
changeIndex(window, 'carname', "Honda"); // The value has changed for: carname
changeIndex(window, 'carNumber', 4); // The value has changed for: carNumber
If you always wanted to pull from the window object you can modify changeIndex to always set obj to be window.
function should_i_go_now() {
if(trafficLightIsGreen && !someoneIsRunningTheLight) {
go();
} else {
setTimeout(function(){
should_i_go_now();
},30);
}
}
setTimeout(function(){
should_i_go_now();
},30);
If you were willing to have about a 1 millisecond delay between checks, you could place
window.setInterval()
on it, for example this won't crash your browser:
window.setInterval(function() {
if (trafficLightIsGreen && !someoneIsRunningTheLight) {
go();
}
}, 1);

jQuery 'if' statement not working

This should be a simple if statement, but it's not working for me. Essentially, when you click an element, I want that element to be highlighted and the ID to be put into a the variable value. However, if in the situation the same element is clicked twice, I want to value = NULL.
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) {
var value = $(this).attr('id');
} else {
value = NULL;
}
});
})(jQuery);
Your primary problem is that you're "hoisting" the value variable by redefining it with the var keyword. This code can also be written more efficiently with a lot less code. This should work:
(function($) {
// somewhere outside click handler
var value = '';
// click handler
$(".list").click(function() {
var id = $(this).toggleClass('hilite').attr('id');
value = (value === id) ? null : id;
/* or if you prefer an actual if/else...
if (value === id) {
value = null;
else {
value = id;
}
*/
});
})(jQuery);
Edit: a couple general comments about the original snippet that might be useful:
NULL should be null
Try not to run the same selector multiple times, or recreate a jQuery object from the same DOM object multiple times - it's much more efficient and maintainable to simply cache the result to a variable (e.g., var $this = $(this);)
Your comparison there is probably "safe", but better to use !== than != to avoid unintentional type coercion.
Not sure how exactly you intended to use value in the original example, but always remember that variables are function-scoped in JavaScript, so your var value statement is hoisting the value identifier for that entire function, which means your assignments have no effect on anything outside that click handler.
You need to declare var value outside the scope of the function, so that its value is maintained across function calls. As it is, the value variable is lost right after it is set, because it goes out of scope.
var value = null;
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) {
value = temp;
} else {
value = null;
}
});
})(jQuery);
You could do:
(function($){
var tmp = {};
$(".list").click(function() {
$(this).toggleClass("hilite");
var id = $(this).attr('id');
if (!tmp[id]) {
var value = id;
tmp[id] = true;
} else {
value = NULL;
tmp[id] = false;
}
});
})(jQuery);
In this way you use a tmp object that stores the state for all the different id's
It might not be skipping that statement, you might just be getting a confusion over the implied global "value" and the local "value".
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) { // <-----------------Implied global var called "value"
var value = $(this).attr('id'); // <---Local variable valled "value"
} else {
value = NULL; // <---------------------Which one am I
}
});
})(jQuery);
Also, it ought to be value = null as NULL is just an undefined variable.
This should be a working example of both points:
var value = null;
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) {
value = $(this).attr('id');
} else {
value = null;
}
});
})(jQuery);
Do you not need to declare value before you use it in the conditional statement?
you aren't setting a value in this function.
var value = "NULL";
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) {
value = $(this).attr('id');
} else {
value = "NULL";
}
});
})(jQuery);
The variable value is not defined. And it either needs to be a global variable or you could use jQuery's $('.selector).data() method to attach it to the element:
http://api.jquery.com/data/
I also recommend using !== for the comparison, since that compares the type of the variable as well as the content.

JavaScript isset() equivalent

In PHP you can do if(isset($array['foo'])) { ... }. In JavaScript you often use if(array.foo) { ... } to do the same, but this is not exactly the same statement. The condition will also evaluate to false if array.foo does exists but is false or 0 (and probably other values as well).
What is the perfect equivalent of PHP's isset in JavaScript?
In a broader sense, a general, complete guide on JavaScript's handling of variables that don't exist, variables without a value, etc. would be convenient.
Update: 11 years and 11 months ago I posted this question, and wow, it still gets a lot of activity. Now, I'm pretty sure that when I wrote this, I only wanted to know how to check for the presence of a property in an associative array (a.k.a. dictionary), and as such the correct (for me) answers involve hasOwnProperty or the in operator. I wasn't interested in checking local or global variables.
But while I remember that well, that intent is not quite clear in the question as written, or even directly contradicted by it! I never mentioned the associative array, and PHP's isset does also do those other things. Let this be a lesson to all of us about how important it is to properly state your requirements in a question, and also how global variables, local variables, object properties, dictionary keys and what-have-you aren't Huey, Dewey, and Louie.
In the meantime (heh), many many people have provided answers to that effect as well, so for those of you who found this question through Google, well, I'm glad my vagueness helped in a way I guess. Anyway, just wanted to clarify that.
I generally use the typeof operator:
if (typeof obj.foo !== 'undefined') {
// your code here
}
It will return "undefined" either if the property doesn't exist or its value is undefined.
(See also: Difference between undefined and not being defined.)
There are other ways to figure out if a property exists on an object, like the hasOwnProperty method:
if (obj.hasOwnProperty('foo')) {
// your code here
}
And the in operator:
if ('foo' in obj) {
// your code here
}
The difference between the last two is that the hasOwnProperty method will check if the property exist physically on the object (the property is not inherited).
The in operator will check on all the properties reachable up in the prototype chain, e.g.:
var obj = { foo: 'bar'};
obj.hasOwnProperty('foo'); // true
obj.hasOwnProperty('toString'); // false
'toString' in obj; // true
As you can see, hasOwnProperty returns false and the in operator returns true when checking the toString method, this method is defined up in the prototype chain, because obj inherits form Object.prototype.
Age old thread, but there are new ways to run an equivalent isset().
ESNext (Stage 4 December 2019)
Two new syntax allow us to vastly simplify the use of isset() functionality:
Optional Chaining(?.)
Nullish Coalescing Operator(??)
Please read the docs and mind the browser compatibility.
Answer
See below for explanation. Note I use StandardJS syntax
Example Usage
// IMPORTANT pass a function to our isset() that returns the value we're
// trying to test(ES6 arrow function)
isset(() => some) // false
// Defining objects
let some = { nested: { value: 'hello' } }
// More tests that never throw an error
isset(() => some) // true
isset(() => some.nested) // true
isset(() => some.nested.value) // true
isset(() => some.nested.deeper.value) // false
// Less compact but still viable except when trying to use `this` context
isset(function () { return some.nested.deeper.value }) // false
Answer Function
/**
* Checks to see if a value is set.
*
* #param {Function} accessor Function that returns our value
* #returns {Boolean} Value is not undefined or null
*/
function isset (accessor) {
try {
// Note we're seeing if the returned value of our function is not
// undefined or null
return accessor() !== undefined && accessor() !== null
} catch (e) {
// And we're able to catch the Error it would normally throw for
// referencing a property of undefined
return false
}
}
NPM Package
This answer function is available as the isset-php package on NPM. The package contains a few improvements such as type checking and supporting multiple arguments.
npm install --save isset-php
The full documentation is available in the README.
const isset = require('isset-php')
let val = ''
// This will evaluate to true so the text will be printed.
if (isset(() => val)) {
console.log('This val is set so I will print.')
}
Explanation
PHP
Note that in PHP you can reference any variable at any depth - even trying to
access a non-array as an array will return a simple true or false:
// Referencing an undeclared variable
isset($some); // false
$some = 'hello';
// Declared but has no depth(not an array)
isset($some); // true
isset($some['nested']); // false
$some = ['nested' => 'hello'];
// Declared as an array but not with the depth we're testing for
isset($some['nested']); // true
isset($some['nested']['deeper']); // false
JavaScript
In JavaScript, we don't have that freedom; we'll always get an error if we do
the same because the engine is immediately attempting to access the value of deeper before we can wrap it in our isset() function so...
// Common pitfall answer(ES6 arrow function)
const isset = (ref) => typeof ref !== 'undefined'
// Same as above
function isset (ref) { return typeof ref !== 'undefined' }
// Referencing an undeclared variable will throw an error, so no luck here
isset(some) // Error: some is not defined
// Defining a simple object with no properties - so we aren't defining
// the property `nested`
let some = {}
// Simple checking if we have a declared variable
isset(some) // true
// Now trying to see if we have a top level property, still valid
isset(some.nested) // false
// But here is where things fall apart: trying to access a deep property
// of a complex object; it will throw an error
isset(some.nested.deeper) // Error: Cannot read property 'deeper' of undefined
// ^^^^^^ undefined
More failing alternatives:
// Any way we attempt to access the `deeper` property of `nested` will
// throw an error
some.nested.deeper.hasOwnProperty('value') // Error
// ^^^^^^ undefined
// Similar to the above but safe from objects overriding `hasOwnProperty`
Object.prototype.hasOwnProperty.call(some.nested.deeper, 'value') // Error
// ^^^^^^ undefined
// Same goes for typeof
typeof some.nested.deeper !== 'undefined' // Error
// ^^^^^^ undefined
And some working alternatives that can get redundant fast:
// Wrap everything in try...catch
try {
if (isset(some.nested.deeper)) {
// ...
}
} catch (e) {}
try {
if (some.nested.deeper !== undefined && some.nested.deeper !== null) {
// ...
}
} catch (e) {}
// Or by chaining all of the isset which can get long
isset(some) && isset(some.nested) && isset(some.nested.deeper) // false
// ^^^^^^ returns false so the next isset() is never run
Conclusion
All of the other answers - though most are viable...
Assume you're only checking to see if the variable is not undefined which
is fine for some use cases but can still throw an Error
Assume you're only trying to access a top level property, which again is
fine for some use cases
Force you to use a less than ideal approach relative to PHP's isset()
e.g. isset(some, 'nested.deeper.value')
Use eval() which works but I personally avoid
I think I covered a lot of it. There are some points I make in my answer that I
don't touch upon because they - although relevant - are not part of the
question(e.g. short circuiting). If need be, though, I can update my answer with links to some of the
more technical aspects based on demand.
I spent waaay to much time on this so hopefully it helps people out.
Thank-you for reading!
Reference to SOURCE
module.exports = function isset () {
// discuss at: http://locutus.io/php/isset/
// original by: Kevin van Zonneveld (http://kvz.io)
// improved by: FremyCompany
// improved by: Onno Marsman (https://twitter.com/onnomarsman)
// improved by: Rafał Kukawski (http://blog.kukawski.pl)
// example 1: isset( undefined, true)
// returns 1: false
// example 2: isset( 'Kevin van Zonneveld' )
// returns 2: true
var a = arguments
var l = a.length
var i = 0
var undef
if (l === 0) {
throw new Error('Empty isset')
}
while (i !== l) {
if (a[i] === undef || a[i] === null) {
return false
}
i++
}
return true
}
phpjs.org is mostly retired in favor of locutus
Here is the new link http://locutus.io/php/var/isset
if (!('foo' in obj)) {
// not set.
}
//
// tring to reference non-existing variable throws ReferenceError
// before test function is even executed
//
// example, if you do:
//
// if ( isset( someVar ) )
// doStuff( someVar );
//
// you get a ReferenceError ( if there is no someVar... )
// and isset fn doesn't get executed.
//
// if you pass variable name as string, ex. isset( 'novar' );,
// this might work:
//
function isset ( strVariableName ) {
try {
eval( strVariableName );
} catch( err ) {
if ( err instanceof ReferenceError )
return false;
}
return true;
}
//
//
This simple solution works, but not for deep object check.
function isset(str) {
return window[str] !== undefined;
}
I always use this generic function to prevent errrors on primitive variables as well as arrays and objects.
isset = function(obj) {
var i, max_i;
if(obj === undefined) return false;
for (i = 1, max_i = arguments.length; i < max_i; i++) {
if (obj[arguments[i]] === undefined) {
return false;
}
obj = obj[arguments[i]];
}
return true;
};
console.log(isset(obj)); // returns false
var obj = 'huhu';
console.log(isset(obj)); // returns true
obj = {hallo:{hoi:'hoi'}};
console.log(isset(obj, 'niet')); // returns false
console.log(isset(obj, 'hallo')); // returns true
console.log(isset(obj, 'hallo', 'hallo')); // returns false
console.log(isset(obj, 'hallo', 'hoi')); // returns true
This solution worked for me.
function isset(object){
return (typeof object !=='undefined');
}
If you are using underscorejs I always use
if (!_.isUndefined(data) && !_.isNull(data)) {
//your stuff
}
This is a pretty bulletproof solution for testing if a variable exists :
var setOrNot = typeof variable !== typeof undefined ? true : false;
Unfortunately, you cannot simply encapsulate it in a function.
You might think of doing something like this :
function isset(variable) {
return typeof variable !== typeof undefined ? true : false;
}
However, this will produce a reference error if variable variable has not been defined, because you cannot pass along a non-existing variable to a function :
Uncaught ReferenceError: foo is not defined
On the other hand, it does allow you to test whether function parameters are undefined :
var a = '5';
var test = function(x, y) {
console.log(isset(x));
console.log(isset(y));
};
test(a);
// OUTPUT :
// ------------
// TRUE
// FALSE
Even though no value for y is passed along to function test, our isset function works perfectly in this context, because y is known in function test as an undefined value.
window.isset = function(v_var) {
if(typeof(v_var) == 'number'){ if(isNaN(v_var)){ return false; }}
if(typeof(v_var) == 'undefined' || v_var === null){ return false; } else { return true; }
};
plus Tests:
https://gist.github.com/daylik/24acc318b6abdcdd63b46607513ae073
(typeof SOMETHING) !== 'undefined'
It's too long to write when used. But we can't package the typeof keyword into a function, because an error will thrown before the function is called, like this:
function isdef($var) {
return (typeof $var) !== 'undefined';
}
isdef(SOMETHING); ///// thrown error: SOMETHING is not defined
So I figured out a way:
function isdef($type) {
return $type !== 'undefined';
}
isdef(typeof SOMETHING);
It can work both with individual variables (variables that does not exist at all), or object properties (non-existent properties). And only 7 more characters than PHP isset.
function isset(variable) {
try {
return typeof eval(variable) !== 'undefined';
} catch (err) {
return false;
}
}
To check wether html block is existing or not, I'm using this code:
if (typeof($('selector').html()) != 'undefined') {
// $('selector') is existing
// your code here
}
Provide the object path as a string, then you can break this string into a path and resolve hasOwnProperty at each step while overwriting the object itself with each iteration.
If you are coding in ES6 environment, take a look at this stackoverflow Ques.
var a;
a = {
b: {
c: 'e'
}
};
function isset (obj, path) {
var stone;
path = path || '';
if (path.indexOf('[') !== -1) {
throw new Error('Unsupported object path notation.');
}
path = path.split('.');
do {
if (obj === undefined) {
return false;
}
stone = path.shift();
if (!obj.hasOwnProperty(stone)) {
return false;
}
obj = obj[stone];
} while (path.length);
return true;
}
console.log(
isset(a, 'b') == true,
isset(a, 'b.c') == true,
isset(a, 'b.c.d') == false,
isset(a, 'b.c.d.e') == false,
isset(a, 'b.c.d.e.f') == false
);
I use a function that can check variables and objects. very convenient to work with jQuery
function _isset (variable) {
if(typeof(variable) == "undefined" || variable == null)
return false;
else
if(typeof(variable) == "object" && !variable.length)
return false;
else
return true;
};
Try to create function like empty function of PHP in Javascript.
May this helps.
function empty(str){
try{
if(typeof str==="string"){
str=str.trim();
}
return !(str !== undefined && str !== "undefined" && str !== null && str!=="" && str!==0 && str!==false);
}catch(ex){
return true;
}
}
console.log(empty(0))//true
console.log(empty(null))//true
console.log(empty(" "))//true
console.log(empty(""))//true
console.log(empty(undefined))//true
console.log(empty("undefined"))//true
var tmp=1;
console.log(empty(tmp))//false
var tmp="Test";
console.log(empty(tmp))//false
var tmp=" Test ";
console.log(empty(tmp))//false
var tmp={a:1,b:false,c:0};
console.log(empty(tmp.a))//false
console.log(empty(tmp.b))//true
console.log(empty(tmp.c))//true
console.log(empty(tmp.c))//true
console.log(empty(tmp.c.d))//true
finally i solved problem with easy solution :
if (obj && obj.foo && obj.foo='somethings'){
console.log('i,m work without error')
}
PHP Manual say:
isset — Determine if a variable is set and is not NULL
And interface something like this:
bool isset ( mixed $var [, mixed $... ] )
The parameter $var is the variable to be checked. it can have any number of parameter though.
isset() returns TRUE if var exists and has value other than NULL. FALSE otherwise.
Some example:
$foo = 'bar';
var_dump(isset($foo)); -> true
$baz = null;
var_dump(isset($baz)); -> false
var_dump(isset($undefined)); -> false
As this in mind, Apparently, It's not possible to write exact equivalent of php isset() function.
For example when we call like this:
if (isset(some_var)) {
}
function issset() {
// function definition
}
Javascript trigger Uncaught ReferenceError: some_var is not defined at (file_name):line_number.
The important and remarkable thing about this behavior is that when trying to pass non-existent variables to normal functions, an error is triggered.
But in PHP isset() are not actually regular functions but language constructs. That means they're part of the PHP language itself, do not play by the normal rules of functions and can hence get away with not triggering an error for non-existent variables. This is important when trying to figure out whether a variable exists or not. But in javscript, it triggers an error in the first place say function call with non-existent variables.
My point is that we can't write it as equivlent javscript function but we can do something like this
if (typeof some_var !== 'undefined') {
// your code here
}
If you want exact same effect PHP also check varable is not NULL
For example
$baz = null;
var_dump(isset($baz)); -> false
So, we can incorporate this into javascript then it look like this:
if (typeof some_var !== 'undefined' && some_var !== null) {
// your code here
}
It was really a problem for me when I was accessing a deeper property of an object so I made a function which will return the property value if exist otherwise it will return false. You may use it to save your time,
//Object on which we want to test
var foo = {
bar: {
bik: {
baz: 'Hello world'
}
}
};
/*
USE: To get value from the object using it properties supplied (Deeper),
if found it will return the property value if not found then will return false
You can use this function in two ways
WAY - 1:
Passing an object as parameter 1 and array of the properties as parameter 2
EG: getValueFromObject(foo, ['bar', 'bik', 'baz']);
WAY - 2: (This will work only if, your object available in window object)
Passing an STRING as parameter 1(Just similarly how we retrieve value form object using it's properties - difference is only the quote)
EG: getValueFromObject('foo.bar.bik.baz');
*/
function getValueFromObject(object, properties) {
if(typeof(object) == 'string') { //Here we extract our object and it's properties from the string
properties = object.split('.');
object = window[properties[0]];
if(typeof(object) == 'undefined') {
return false;
}
properties.shift();
}
var property = properties[0];
properties.shift();
if(object != null && typeof(object[property]) != 'undefined') {
if(typeof(object[property]) == 'object') {
if(properties.length != 0) {
return getValueFromObject(object[property], properties); //Recursive call to the function
} else {
return object[property];
}
} else {
return object[property];
}
} else {
return false;
}
}
console.log(getValueFromObject('fooo.bar.bik.baz')); //false
console.log(getValueFromObject('foo.bar.bik.baz')); //Hello world
console.log(getValueFromObject('foo')); //false
console.log(getValueFromObject('foo.bar.bik')); //returns an object { baz: 'Hello World' }
console.log(getValueFromObject(foo, ['bar', 'bik'])); //returns an object { baz: 'Hello World' }
console.log(getValueFromObject(foo, ['bar', 'bik', 'baz']));//Hello world
If you want to check if an element exists, just use the following code:
if (object) {
//if isset, return true
} else {
//else return false
}
This is sample:
function switchDiv() {
if (document.querySelector("#divId")) {
document.querySelector("#divId").remove();
} else {
var newDiv = document.createElement("div");
newDiv.id = "divId";
document.querySelector("body").appendChild(newDiv);
}
}
document.querySelector("#btn").addEventListener("click", switchDiv);
#divId {
background: red;
height: 100px;
width: 100px;
position: relative;
}
<body>
<button id="btn">Let's Diiiv!</button>
</body>
Be careful in ES6, all the previous solutions doesn't work if you want to check a declaration of a let variable and declare it, if it isn't
example
let myTest = 'text';
if(typeof myTest === "undefined") {
var myTest = 'new text'; // can't be a let because let declare in a scope
}
you will see a error
Uncaught SyntaxError: Identifier 'myTest' has already been declared
The solution was to change it by a var
var myTest = 'text'; // I replace let by a var
if(typeof myTest === "undefined") {
var myTest = 'new text';
}
another solution if you can change a let by a var, you need to remove your var
let myTest = 'text';
if(typeof myTest === "undefined") {
myTest = 'new text'; // I remove the var declaration
}
try {
const value = array.foo.object.value;
// isset true
} catch (err) {
// isset false
}
use this function for arrays or nested array (but not for strings)
if(isset(array,'key1=>key1')){alert('isset');}
https://jsfiddle.net/dazzafact/cgav6psr/
arr={nested:{nested2:{val:'isset'}}}
if(t=isset(arr,'nested=>nested2=>val','=>')){
alert(t)
}
function isset(obj,nested,split) {
var sep=split || '.';
var dub=obj
var isset=false
if(typeof(obj)!="undefined" && typeof(nested)!="undefined"){
var arr=nested.split(sep);
for(var k in arr){
var key=arr[k];
if(typeof(dub[key])=="undefined"){
isset=false;
break;
}
dub=dub[key];
isset=dub
}
}
return isset;
}
isset('user.permissions.saveProject', args);
function isset(string, context) {
try {
var arr = string.split('.');
var checkObj = context || window;
for (var i in arr) {
if (checkObj[arr[i]] === undefined) return false;
checkObj = checkObj[arr[i]];
}
return true;
} catch (e) {
return false;
}
}
if (var) {
// This is the most concise equivalent of Php's isset().
}
javascript isset
let test = {
a: {
b: [0, 1]
}
};
console.log(test.isset('a.b')) // true
console.log(test.isset('a.b.1')) // true
console.log(test.isset('a.b.5')) // false
console.log(test.isset('a.c')) // false
console.log('abv'.isset('0')) // true
This is the most concise equivalent of Php's isset() :
if(var == undefined)
true this is var !isset
false this is var isset

Categories