How this assignment and control flow of JAVASCRIPT code works - javascript

In the following code, how the statement works, as this statement is the part of an javascript file.
this.isSelected = function(checkTab)
{
return(this.tab===checkTab);
}

this.isSelected is a function, taking checkTab as a parameter. It compares it to this.tab and returns true if they are equal, otherwise false.
this.isSelected = function(checkTab)
{
return (this.tab === checkTab);
}
// equivalent to
function isSelected(checkTab) {
if(this.tab === checkTab) return true;
return false;
}

Related

Check property exist in object or not in JavaScript?

I have one problem statement.
Implement a function propertyExists(obj, path) that takes in an object and a path (string) as arguments and returns ‘False’ if the property doesn’t exist on that object or is null, else returns the value of the property.
And here is solution.
function propertyExists(obj,path) {
// Write logic here
let result = obj.hasOwnProperty(path);
if(result)
{
return (obj.path);
}
else
{
return result;
}
}
Is this correct way of doing it?
Multiple issues:
the first name of the function should represent what it is doing,
Path as variable name is vague but propertyName as a variable is clear.
what you should do is either:
write function called, "getValue" it returns value if exist or null
function getValue(obj,propertyName) {
if(!obj) { // if object not exist
return null;
}
return obj[propertyName];
}
write function called, "propertyExists" should return true if exist else false.
function propertyExists(obj,propertyName) {
if(!obj) { // if object not exist
return false;
}
return obj.hasOwnProperty(propertyName);
}
function propertyExists(obj,path) {
// Write logic here
for(i in path){
if(obj.hasOwnProperty(path[i]) === true){
obj = obj[path[i]];
}else{
return false;
}
}
return obj;
}
object->obj,propertyname->path
function propertyExist(obj, path){
if (obj.hasOwnProperty(path)) return obj[path];
else return false;
};
Here, as far as I can understand, the objects could be nested also.
Let's take obj as {"a":{"b":"dadsa"}} and path as ab
Now, the the solution which you have posted will not work. Ideally, it should return dadsa, but it will return false.
Try the below code, it will work for nested objects also.
function propertyExists(obj,path) {
// Write logic here
var val=obj;
for(a of path){
val=val[a];
if(!val)
return false;
}
return val;
}
function propertyExists(obj,path) {
var val = obj;
for (a of path) {
val = val[a];
if (!val){
return false;
}
return val;
}

Trying to solve If/else problem with specific string and boolean

Problem
I've tried multiple avenues and watched videos. I'm stuck...
function exerciseThree(typeOfPizza){
let lovesPizza;
// In this exercise, you will be given a variable, it will be called: typeOfPizza
// You are also given another variable called: lovesPizza;
// Using an if/else statement assign lovesPizza to true if typeOfPizza is 'pepperoni', assign it to false if it is 'olives'
What I've tried:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
Another attempt
// if(lovesPizza===pepperoni){
// return true
//}
//else (lovesPizza===olives){
// return false
// }
Another one
//if (lovesPizza.equals(pepperoni))
// return "true";
//else (lovesPizza.equals(olives))
// return "false"
As the comments say, you're looking for if / else. You should also double check your reading of the question, you had your checking / assigning variables the wrong way around
function exerciseThree(typeOfPizza){
let lovesPizza;
if (typeOfPizza === 'pepperoni') {
lovesPizza = true;
} else if (typeOfPizza === 'olives') {
lovesPizza = false;
}
console.log('lovesPizza:', lovesPizza);
};
exerciseThree('pepperoni');
exerciseThree('olives');
I would highly recommend using a switch statement in this case here. Switch statements run faster and are easier to work with in my opinion.
But to point out what you're doing wrong:
Here you are checking if lovesPizza has the value of pepperoni. But you should be checking typeOfPizza. This is why you're most likely getting undefined:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
Check out how this looks with a switch statement.
function exerciseThree(typeOfPizza) {
switch (typeOfPizza) {
case 'pepperoni':
return true;
case 'olives':
return false;
default:
return false;
}
}
exerciseThree('pepperoni');
exerciseThree('olives');
Your else statement needs an if
if(somethingisTrue)
{
return "it is true";
}
else if(somethingelseistrue)
{
return "no the other thing was true";
}
else
{
return "nothing is true"
}
Also === checks the strings equal and are both strings. It is often better to make sure the if is case insensative
if(!typeOfPizza)
{
//raise an error as null was passed in
return "false"
}
else if(typeOfPizza.toLowerCase().trim()==="pepperoni"){
{
return true..... you can build the rest
I often write a function (prototype) called cleanString or compareString to perform all the normal cleaning up of strings.
A simple solution is but doesn't use ifs as asked.
function exerciseThree(typeOfPizza){
let lovesPizza= typeOfPizza==="pepperoni";
return lovesPizza;
}
I certainly hope you teacher is playing a trick on you.
There is no sane suggestions what to do if you send for instance 'ham' into it, and not handle all possibilities are just sloppy.
let lovesPizza;
function exerciseThree(typeOfPizza){
if(typeOfPizza === 'pepperoni') {
return true;
} else if (typeOfPizza === 'olives') {
return false;
} else {
return undefined;
}
}
lovesPizza = exerciseThree('pepperoni');
console.log(lovesPizza); // true
lovesPizza = exerciseThree('olives');
console.log(lovesPizza); // false
lovesPizza = exerciseThree('ham');
console.log(lovesPizza); // undefined

Boolean conditions in javascript

Can't understand how I possibly can check value given in function. All my known methods fails. Sorry for lame question!:)
# doesn't work, but should to
window.mobilecheck = function() {
return true;
}
if (window.mobilecheck==true) {
alert('true');
}
# works, but shouldn't
window.mobilecheck = function() {
return false;
}
if (window.mobilecheck) {
alert('true');
}
# doesn't work, but should
window.mobilecheck = function() {
return 1;
}
if (window.mobilecheck==1) {
alert('true');
}
So how to check if function returns true or false if this doesn't work?
When you use window.mobilecheck you get the function, not the evaluation/return value of the function. Use to window.mobilecheck() ==1 to evaluate your function.

How can I assign value returned from anon function?

Is it possible to avoid declaring global variable and instead assign it the result of the anonymous function?
var logged = false;
Ext.each(userRecords, function (userRecord) {
if (userRecord.get('id') == currentuser) {
if (userRecord.get('password') == currentuserpassword) {
logged = true;
}
}
});
Example:
var logged = Ext.each(userRecords, function (userRecord) {
if (userRecord.get('id') == currentuser) {
if (userRecord.get('password') == currentuserpassword) {
return true;
}
}
});
If you're using Ext JS 4.0 or later, just replace your Ext.each in the second code block with Ext.Array.some and your code will work as is.
Executes the specified function for each array element until the function returns a truthy value. If such an item is found, the function will return true immediately. Otherwise, it will return false.
Using ECMAScript 5 some array method:
var logged = userRecords.some(function (userRecord) {
if (userRecord.get('id') == currentuser) {
if (userRecord.get('password') == currentuserpassword) {
return true;
}
}
return false;
});

javascript recursion in loop return statement not working

I have a loop in which I have a recursive function which does not return and stop. Here is code
var obj = {
here: { is: "an" },
object: 2
};
var obj1 = {
here: { is: "aan" },
object: 2
};
function objectTester(x) {
if (typeof x === 'object' && x !== null)
return true;
else
return false;
}
function deepEqual(valOne, valTwo) {
debugger
if (objectTester(valOne) && objectTester(valTwo)) {
for (key in valOne) {
if (valTwo.hasOwnProperty(key)) {
if (objectTester(valOne[key]) && objectTester(valTwo[key])) {
deepEqual(valOne[key], valTwo[key]);
}
else {
if (valOne[key] === valTwo[key]) {
}
else {
return false; //function dose not stop executing and return false
}
}
}
else {
return false;
}
}
return true;
}
else {
return false;
}
}
console.log(deepEqual(obj, obj1));
Link
When you call deepEqual recursively here:
if (objectTester(valOne[key]) && objectTester(valTwo[key])) {
deepEqual(valOne[key], valTwo[key]);
}
you are ignoring the return value from the recursive call so its gonna loop over everything irrespective of the inner objects being equal or not.
Try
if(!deepEqual(valOne[key], valTwo[key])){ return false }
Another alternative is throwing an exception (and catching it at the top) instead of returning booleans. This makes your control flow jump straight out no matter how many levels of recursion you have.

Categories

Resources