what happens to a javascript variable assign with a non existent variable - javascript

I'm assigning a javascript variable with a value as
var newline = $("#newline").val();
The $("#newline").val() may or may not exist (in some cases, the #newline may not exist in the DOM, or even if it exists, it may not have any value).
I want to check whether the var newline is set or not. How do I do that?

This comes down to "What does the jQuery val method return if there are no elements matching the selector in the DOM?"
The answer to that is undefined so:
if ( typeof newline === "undefined" ) {
}

jQuery:
(function() {
if (this && this[0] && this[0].value) {
// Has a value
} else {
// Has no value
}
}).call($("#newline"));
this[0] is the HTML Element itself, rather than a jQuery Object.
Pure JavaScript:
(function() {
if (this && this.value) {
// Has a value
} else {
// Has no value
}
}).call(document.getElementById("newline"));

Related

How to check if module function exist in Node js

I have created a module and defined functions in it. Sometimes I need to check if a certain function is actually already created.
For example
var newyork = function() {
console.log("newyork");
};
var washington = function() {
console.log("washington");
};
exports.newyork = newyork;
exports.washington = washington;
Now in the different file, I want to first check if the function exists, something like:
var cities = require('./city');
if(cities.newyork) {
console.log("city function exist");
}
else {
//false
}
As I said in the comments what you wrote actually works because
if(cities.newyork){
Checks if cities.newyork is truthy. The following things are truthy:
functions (thats why it works here)
numbers except 0
strings except an empty one
objects / arrays
If it is however not defined, cities.newyork will be undefined which is falsy (will enter the else branch)
typeof cities.cityName === 'function'
if city's name is assigned to some variable
typeof cities[cityName] === 'function'

How to find if element with specific id exists or not

In my JavaScript I want to check whether the element with specific id is exist or not, I tried it with 2 ways
1).
var myEle = document.getElementById("myElement");
if(myEle == null){
var myEleValue= document.getElementById("myElement").value;
}
2).
if(getElementById("myElement")){
var myEleValue= document.getElementById("myElement").value;
}
but it gives same error as below -
Object expected
var myEle = document.getElementById("myElement");
if(myEle) {
var myEleValue= myEle.value;
}
the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value
You can simply use if(yourElement)
var a = document.getElementById("elemA");
var b = document.getElementById("elemB");
if(a)
console.log("elemA exists");
else
console.log("elemA does not exist");
if(b)
console.log("elemB exists");
else
console.log("elemB does not exist");
<div id="elemA"></div>
getElementById
Return Value: An Element Object, representing an element with the specified ID. Returns null if no elements with the specified ID exists
see: https://www.w3schools.com/jsref/met_document_getelementbyid.asp
Truthy vs Falsy
In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN). see: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
When the dom element is not found in the document it will return null. null is a Falsy and can be used as boolean expression in the if statement.
var myElement = document.getElementById("myElement");
if(myElement){
// Element exists
}
You need to specify which object you're calling getElementById from. In this case you can use document. You also can't just call .value on any element directly. For example if the element is textbox .value will return the value, but if it's a div it will not have a value.
You also have a wrong condition, you're checking
if (myEle == null)
which you should change to
if (myEle != null)
var myEle = document.getElementById("myElement");
if(myEle != null) {
var myEleValue= myEle.value;
}
document.getElementById('yourId')
is the correct way.
the document refers the HTML document that is loaded in the DOM.
and it searches the id using the function getElementById()
which takes a parameter of the id of an element
Solution will be :
var elem = (document.getElementById('myElement'))? document.getElementById('myElement').value : '';
/* this will assign a value or give you and empty string */
Use typeof for elements checks.
if(typeof(element) === 'undefined')
{
// then field does not exist
}
if( document.getElementById("myElement") ){
console.log('exists');
}
or shorter way
if( document.querySelector("#myElement") ){}
this works for me to check if element exits
let element = document.getElementById("element_id");
if (typeof(element) !== 'undefined' && element!== null)
{
//content
}

How to replace a dynamically specified attribute in JS object

The attribute(or the nested object) is selected dynamically based on conditions. It can be one of the 4 possibilities as follows:
var tempData = o.title ? o["properties"] || o["items"]["properties"] : o[k]["properties"] || o[k]["items"]["properties"];
Then I get this new data, I want to replace the above selected with.
var newData = //some new Object
I want to replace whatever above selected with the new data. I could do the following (go through the condition again and set the new data):
if(o.title){
if (o["properties"]) {
o["properties"] = newData;
} else if (o["items"]["properties"]) {
o["items"]["properties"] = newData;
}
}else{
if (o[k]["properties"]) {
o[k]["properties"] = newData;
} else if (o[k]["items"]["properties"]) {
o[k]["items"]["properties"] = newData;
}
}
But it doesn't look good. What is the more sophisticated way of achieving this?
It is unclear if you are generically attempting to replace any properties property with the newData, or if you are wanting it to specifically be one of the ones you have specified in your code. I have assumed that you are only wanting to replace the ones you specifically have shown in your code.
Note: The following assumes that it is not possible for the value of the properties property to evaluate to false. If it is possible for it to have a value that evaluates to false, this will fail.
As a first pass, I would do something like:
var p;
if (o.title) {
p=o;
} else {
p=o[k];
}
if (p.properties) {
p.properties = newData;
} else if (p.items.properties) {
p.items.properties = newData;
}
However, that relies on:
o is not null or undefined.
o.title does not evaluate to false, if you are trying to test for the existence of o.title.
k is valid/defined.
p (i.e. o[k]) is not null or undefined (i.e. is an Object)
p.properties does not evaluate to false, if you are testing for existence
p.items is not null or undefined (i.e. is an Object)
p.items.properties does not evaluate to false, if you are testing for existence
A more robust implementation would be:
if (typeof o === 'object' && o !== null) {
var p;
if (o.hasOwnProperty('title')) {
p = o;
} else {
p = o[k];
}
if (typeof p === 'object' && p !== null) {
if (p.hasOwnProperty('properties')) {
p.properties = newData;
} else if (typeof p.items === 'object' && p.items !== null
&& p.items.hasOwnProperty('properties')) {
p.items.properties = newData;
}
}
}
This still relies on:
k is valid/defined.
Basically, it is OK to use shortcuts like if(o.title) to test for existence, if you know that
the possible values for o can not include ones which might make your code throw an error (e.g o is null or undefined), and
the possible values for o.title do not evaluate to false when the property actually exists (e.g. o.title is null, undefined (yes, the property can exist, but have the value undefined), false, 0, '', etc.).
If you are going to perform the replacements in other areas of your code, or if you are going to use property keys other than hard coded items, and properties, then you should create a function. Assuming you are only performing this replacement in this section of your code, using a variable to hold the object in which you are looking for properties is faster/more efficient than creating a function.
Ok, from what i can understand here, it's like you are trying to replace the "properties" with the new data, and you want this to be able to be done dynamically, or maybe i can say, you need to do this regardless the structure.
lets see, if your objective is anything that end up with "properties", lets do it like this:
function recReplace(current,target,replacement){
for (var i in current){
if (i == target){
current[i] = replacement;
}
else{
recReplace(current[i],target,replacement);
}
}
}
And in the end you call
recReplace(o,"properties",newData);
But this will replace whole "properties" key with newData in DFS way, you can do additional conditional if you want to replace it only the first occurence

Shorthand for "if typeof undefined" in Javascript?

Is it possible to write this in shorter and cleaner way?
I'm reading it from an XML, sometimes the URL value does not exist.
if (typeof(entry[i].getElementsByTagName("url")[0].childNodes[0]) !== "undefined") {
var foo = 'baar'
} else {
var foo = entry[i].getElementsByTagName("url")[0].childNodes[0]
}
It's been years it doesn't make sense anymore to use this construct (unless you don't know whether the variable, not the value, is undefined). undefined is now read only.
Simply use
if (entry[i].getElementsByTagName("url")[0].childNodes[0] === undefined) {
In almost all cases, typeof x === "undefined" is a bad practice.
In the specific case of a DOM element, you can also simply use
if (!entry[i].getElementsByTagName("url")[0].childNodes[0]) {
because you can't have a falsy node, and of course, when the goal is to apply a default value, just use
var foo = entry[i].getElementsByTagName("url")[0].childNodes[0] || 'baar';
(be careful that this test only works when all the parts before the the last [0] are present, it's usually convenient to use querySelector or a DOM selection API like jQuery to make everything less verbose).
var foo = entry[i].getElementsByTagName("url")[0].childNodes[0] || 'baar'
You can write in this way.
var ele = entry[i].getElementsByTagName("url");
if (ele && ele[0].childNodes[0]) {
var foo = 'baar'
} else {
//code
}
There is no need to check it explicitly for undefined.undefined is evaluated as false.

Checking if a parameter is assigned or not in javascript

I have a function with 2 parameters, it should work whether a the 2nd parameter is assigned or not in the bracket. Basically, if it's assigned then do something if not do something else or just don't bother about it.
vf.showHide = function (trigger, target) {
var $trigger = $(trigger),
trigParent = $trigger.parent(),
trigDataView = $trigger.data('view'),
numShown = $trigger.data('showalways'),
basketSubtotalElem = $('.subtotal .monthlyCost span.price, .subtotal .oneOffCost span.price, .subtotal label h3, .vat *');
target = target || null; // This is the 2nd parameter but I don't know if this right...
trigParent.delegate(trigger, 'click', function (e) {
var elem = $(this);
target = $(elem.attr('href'));
e.preventDefault();
if (trigDataView === 'showhide') {
if($('.filterBlock')){
if (target.is(':visible')) {
target.hide();
elem.find('span').removeClass('minus').addClass('plus');
} else {
target.show();
elem.find('span').removeClass('plus').addClass('minus');
}
}
}
});
}
So if the function is called like this: vf.showHide('a', 'div') it works and if it's called with 1 parameter like this: vf.showHide('a') it's should still works and error is thrown.
Many thanks
When you invoke a function, if you pass fewer parameters than expected, the parameters you omit are given the undefined value. So in your case:
vf.showHide = function(trigger, target) {
if (target === undefined) {
//target parameter is not passed any value or passed undefined value
//add code to process here, e.g. assign target a default value
}
}
target = target || null: if target is evaluated to false, it's assigned to null. Take notice that empty string, zero number (0), NaN, undefined, null, false are evaluated to false. So please be careful to write code like that.
target = target || null will work.
What you are doing here is declare an local variable within the function's scope.
Within each function, a local variable corresponding to the the name of the parameters are created to hold the passed in value.
If the parameters are not passed in, it will remain as 'undefined' local variable.
function (a, b) {
//a, b are declared.
}
what target = target || null does is just assign a value to an declared local variable it use the || expression:
The value of of || expression is determined by the first operands return true.
true || 2 will be valued as true
false || 2 will be valued as 2

Categories