• How it works
  • Homework answers

Physics help

Answer to Question #231951 in HTML/JavaScript Web Application for raj

We have a task to do Gardening.

Given two boolean values

  • isGrassTrimmerFound and isWaterHosePipeFound as inputs, create three JS promises using async/await and try/catch blocks. For cutting the grass,
  • resolve with  "Grass Trimmed"  text, if the isGrassTrimmerFound is true
  • reject with  "Grass Trimmer Not Found"  text, if the isGrassTrimmerFound is false
  • For cleaning the garden,
  • resolve with  "Garden Cleaned"  text
  • For watering the plants,
  • resolve with  "Watered Plants"  text, if the isWaterHosePipeFound is true
  • reject with  "Water Hose Pipe Not Found"  text, if the isWaterHosePipeFound is false

Need a fast expert's response?

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS !

Leave a comment

Ask your question, related questions.

  • 1. Color PaletteIn this assignment, let's build a Color Palette by applying the CSS concepts we le
  • 2. Write a PHP program which will ask the user to key a paragraph or sentence. Then it will help the us
  • 3. Write a PHP program which will ask the user to key a paragraph or sentence. Then it will help the us
  • 4. In this assignment, let's build a Yoga page by applying the concepts we learned till now. You c
  • 5. 5.create a registration form and display the details in the other PHP page. Create a mock registrat
  • 6. Your organization where you work has won different contracts after responding to Request For Proposa
  • 7. a. Using a while loop, write a program to calculate and print the sum of a givennumber of squares. F
  • Programming
  • Engineering

10 years of AssignmentExpert

Who Can Help Me with My Assignment

There are three certainties in this world: Death, Taxes and Homework Assignments. No matter where you study, and no matter…

How to finish assignment

How to Finish Assignments When You Can’t

Crunch time is coming, deadlines need to be met, essays need to be submitted, and tests should be studied for.…

Math Exams Study

How to Effectively Study for a Math Test

Numbers and figures are an essential part of our world, necessary for almost everything we do every day. As important…

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

This Javascript app allows the user to “plant” a digital version of a small garden to help keep track of what's growing, and how to care for it.

jillbowen/garden_planner_frontend

  • JavaScript 55.7%

JavaScript Garden is a growing collection of documentation about the most quirky parts of the JavaScript programming language. It gives advice to avoid common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert JavaScript programmers may encounter on their endeavours into the depths of the language.

JavaScript Garden does not aim to teach you JavaScript. Former knowledge of the language is strongly recommended in order to understand the topics covered in this guide. In order to learn the basics of the language, please head over to the excellent guide on the Mozilla Developer Network.

The Authors

This guide is the work of two lovely Stack Overflow users, Ivo Wetzel (Writing) and Zhang Yi Jiang (Design).

It's currently maintained by Tim Ruffles .

Contributors

  • Too many to list here, see all contributors .

JavaScript Garden is hosted on GitHub, but Cramer Development supports us with a mirror at JavaScriptGarden.info .

JavaScript Garden is published under the MIT license and hosted on GitHub . If you find errors or typos please file an issue or a pull request on the repository. You can also find us in the JavaScript room on Stack Overflow chat.

Object Usage and Properties

Everything in JavaScript acts like an object, with the only two exceptions being null and undefined .

A common misconception is that number literals cannot be used as objects. That is because a flaw in JavaScript's parser tries to parse the dot notation on a number as a floating point literal.

There are a couple of workarounds that can be used to make number literals act as objects too.

Objects as a Data Type

Objects in JavaScript can also be used as Hashmaps ; they mainly consist of named properties mapping to values.

Using an object literal - {} notation - it is possible to create a plain object. This new object inherits from Object.prototype and does not have own properties defined.

Accessing Properties

The properties of an object can be accessed in two ways, via either the dot notation or the square bracket notation.

The notations work almost identically, with the only difference being that the square bracket notation allows for dynamic setting of properties and the use of property names that would otherwise lead to a syntax error.

Deleting Properties

The only way to remove a property from an object is to use the delete operator; setting the property to undefined or null only removes the value associated with the property, but not the key .

The above outputs both bar undefined and foo null - only baz was removed and is therefore missing from the output.

Notation of Keys

Object properties can be both notated as plain characters and as strings. Due to another mis-design in JavaScript's parser, the above will throw a SyntaxError prior to ECMAScript 5.

This error arises from the fact that delete is a keyword ; therefore, it must be notated as a string literal to ensure that it will be correctly interpreted by older JavaScript engines.

The Prototype

JavaScript does not feature a classical inheritance model; instead, it uses a prototypal one.

While this is often considered to be one of JavaScript's weaknesses, the prototypal inheritance model is in fact more powerful than the classic model. It is, for example, fairly trivial to build a classic model on top of a prototypal model, while the other way around is a far more difficult task.

JavaScript is the only widely used language that features prototypal inheritance, so it can take time to adjust to the differences between the two models.

The first major difference is that inheritance in JavaScript uses prototype chains .

In the code above, the object test will inherit from both Bar.prototype and Foo.prototype ; hence, it will have access to the function method that was defined on Foo . It will also have access to the property value of the one Foo instance that is its prototype. It is important to note that new Bar() does not create a new Foo instance, but reuses the one assigned to its prototype; thus, all Bar instances will share the same value property.

Property Lookup

When accessing the properties of an object, JavaScript will traverse the prototype chain upwards until it finds a property with the requested name.

If it reaches the top of the chain - namely Object.prototype - and still hasn't found the specified property, it will return the value undefined instead.

The Prototype Property

While the prototype property is used by the language to build the prototype chains, it is still possible to assign any given value to it. However, primitives will simply get ignored when assigned as a prototype.

Assigning objects, as shown in the example above, will work, and allows for dynamic creation of prototype chains.

Performance

The lookup time for properties that are high up on the prototype chain can have a negative impact on performance, and this may be significant in code where performance is critical. Additionally, trying to access non-existent properties will always traverse the full prototype chain.

Also, when iterating over the properties of an object every property that is on the prototype chain will be enumerated.

Extension of Native Prototypes

One mis-feature that is often used is to extend Object.prototype or one of the other built in prototypes.

This technique is called monkey patching and breaks encapsulation . While used by popular frameworks such as Prototype , there is still no good reason for cluttering built-in types with additional non-standard functionality.

The only good reason for extending a built-in prototype is to backport the features of newer JavaScript engines; for example, Array.forEach .

In Conclusion

It is essential to understand the prototypal inheritance model before writing complex code that makes use of it. Also, be aware of the length of the prototype chains in your code and break them up if necessary to avoid possible performance problems. Further, the native prototypes should never be extended unless it is for the sake of compatibility with newer JavaScript features.

hasOwnProperty

To check whether an object has a property defined on itself and not somewhere on its prototype chain , it is necessary to use the hasOwnProperty method which all objects inherit from Object.prototype .

hasOwnProperty is the only thing in JavaScript which deals with properties and does not traverse the prototype chain.

Only hasOwnProperty will give the correct and expected result. See the section on for in loops for more details on when to use hasOwnProperty when iterating over object properties.

hasOwnProperty as a Property

JavaScript does not protect the property name hasOwnProperty ; thus, if the possibility exists that an object might have a property with this name, it is necessary to use an external hasOwnProperty to get correct results.

Using hasOwnProperty is the only reliable method to check for the existence of a property on an object. It is recommended that hasOwnProperty be used in many cases when iterating over object properties as described in the section on for in loops .

The for in Loop

Just like the in operator, the for in loop traverses the prototype chain when iterating over the properties of an object.

Since it is not possible to change the behavior of the for in loop itself, it is necessary to filter out the unwanted properties inside the loop body. In ECMAScript 3 and older, this is done using the hasOwnProperty method of Object.prototype .

Since ECMAScript 5, Object.defineProperty can be used with enumerable set to false to add properties to objects (including Object ) without these properties being enumerated. In this case it is reasonable to assume in application code that any enumerable properties have been added for a reason and to omit hasOwnProperty , since it makes code more verbose and less readable. In library code hasOwnProperty should still be used since assumptions cannot be made about which enumerable properties might reside on the prototype chain.

Using hasOwnProperty for Filtering

This version is the only correct one to use with older versions of ECMAScript. Due to the use of hasOwnProperty , it will only print out moo . When hasOwnProperty is left out, the code is prone to errors in cases where the native prototypes - e.g. Object.prototype - have been extended.

In newer versions of ECMAScript, non-enumerable properties can be defined with Object.defineProperty , reducing the risk of iterating over properties without using hasOwnProperty . Nonetheless, care must be taken when using older libraries like Prototype , which does not yet take advantage of new ECMAScript features. When this framework is included, for in loops that do not use hasOwnProperty are guaranteed to break.

It is recommended to always use hasOwnProperty in ECMAScript 3 or lower, as well as in library code. Assumptions should never be made in these environments about whether the native prototypes have been extended or not. Since ECMAScript 5, Object.defineProperty makes it possible to define non-enumerable properties and to omit hasOwnProperty in application code.

Function Declarations and Expressions

Functions in JavaScript are first class objects. That means they can be passed around like any other value. One common use of this feature is to pass an anonymous function as a callback to another, possibly an asynchronous function.

The function Declaration

The above function gets hoisted before the execution of the program starts; thus, it is available everywhere in the scope it was defined , even if called before the actual definition in the source.

The function Expression

This example assigns the unnamed and anonymous function to the variable foo .

Due to the fact that var is a declaration that hoists the variable name foo before the actual execution of the code starts, foo is already declared when the script gets executed.

But since assignments only happen at runtime, the value of foo will default to undefined before the corresponding code is executed.

Named Function Expression

Another special case is the assignment of named functions.

Here, bar is not available in the outer scope, since the function only gets assigned to foo ; however, inside of bar , it is available. This is due to how name resolution in JavaScript works, the name of the function is always made available in the local scope of the function itself.

How this Works

JavaScript has a different concept of what the special name this refers to than most other programming languages. There are exactly five different ways in which the value of this can be bound in the language.

The Global Scope

When using this in global scope, it will simply refer to the global object.

Calling a Function

Here, this will again refer to the global object.

Calling a Method

In this example, this will refer to test .

Calling a Constructor

A function call that is preceded by the new keyword acts as a constructor . Inside the function, this will refer to a newly created Object .

Explicit Setting of this

When using the call or apply methods of Function.prototype , the value of this inside the called function gets explicitly set to the first argument of the corresponding function call.

As a result, in the above example the method case does not apply, and this inside of foo will be set to bar .

Common Pitfalls

While most of these cases make sense, the first can be considered another mis-design of the language because it never has any practical use.

A common misconception is that this inside of test refers to Foo ; while in fact, it does not .

In order to gain access to Foo from within test , you can create a local variable inside of method that refers to Foo .

self is just a normal variable name, but it is commonly used for the reference to an outer this . In combination with closures , it can also be used to pass this values around.

As of ECMAScript 5 you can use the bind method combined with an anonymous function to achieve the same result.

Assigning Methods

Another thing that does not work in JavaScript is function aliasing, which is assigning a method to a variable.

Due to the first case, test now acts like a plain function call; therefore, this inside it will no longer refer to someObject .

While the late binding of this might seem like a bad idea at first, in fact, it is what makes prototypal inheritance work.

When method gets called on an instance of Bar , this will now refer to that very instance.

Closures and References

One of JavaScript's most powerful features is the availability of closures . With closures, scopes always keep access to the outer scope, in which they were defined. Since the only scoping that JavaScript has is function scope , all functions, by default, act as closures.

Emulating private variables

Here, Counter returns two closures: the function increment as well as the function get . Both of these functions keep a reference to the scope of Counter and, therefore, always keep access to the count variable that was defined in that scope.

Why Private Variables Work

Since it is not possible to reference or assign scopes in JavaScript, there is no way of accessing the variable count from the outside. The only way to interact with it is via the two closures.

The above code will not change the variable count in the scope of Counter , since foo.hackFail was not defined in that scope. It will instead create - or override - the global variable count .

Closures Inside Loops

One often made mistake is to use closures inside of loops, as if they were copying the value of the loop's index variable.

The above will not output the numbers 0 through 9 , but will simply print the number 10 ten times.

The anonymous function keeps a reference to i . At the time console.log gets called, the for loop has already finished, and the value of i has been set to 10 .

In order to get the desired behavior, it is necessary to create a copy of the value of i .

Avoiding the Reference Problem

In order to copy the value of the loop's index variable, it is best to use an anonymous wrapper .

The anonymous outer function gets called immediately with i as its first argument and will receive a copy of the value of i as its parameter e .

The anonymous function that gets passed to setTimeout now has a reference to e , whose value does not get changed by the loop.

There is another possible way of achieving this, which is to return a function from the anonymous wrapper that will then have the same behavior as the code above.

The other popular way to achieve this is to add an additional argument to the setTimeout function, which passes these arguments to the callback.

Some legacy JS environments (Internet Explorer 9 & below) do not support this.

There's yet another way to accomplish this by using .bind , which can bind a this context and arguments to function. It behaves identically to the code above

The arguments Object

Every function scope in JavaScript can access the special variable arguments . This variable holds a list of all the arguments that were passed to the function.

The arguments object is not an Array . While it has some of the semantics of an array - namely the length property - it does not inherit from Array.prototype and is in fact an Object .

Due to this, it is not possible to use standard array methods like push , pop or slice on arguments . While iteration with a plain for loop works just fine, it is necessary to convert it to a real Array in order to use the standard Array methods on it.

Converting to an Array

The code below will return a new Array containing all the elements of the arguments object.

Because this conversion is slow , it is not recommended to use it in performance-critical sections of code.

Passing Arguments

The following is the recommended way of passing arguments from one function to another.

Another trick is to use both call and apply together to turn methods - functions that use the value of this as well as their arguments - into normal functions which only use their arguments.

Formal Parameters and Arguments Indices

The arguments object creates getter and setter functions for both its properties, as well as the function's formal parameters.

As a result, changing the value of a formal parameter will also change the value of the corresponding property on the arguments object, and the other way around.

Performance Myths and Truths

The only time the arguments object is not created is where it is declared as a name inside of a function or one of its formal parameters. It does not matter whether it is used or not.

Both getters and setters are always created; thus, using it has nearly no performance impact at all, especially not in real world code where there is more than a simple access to the arguments object's properties.

However, there is one case which will drastically reduce the performance in modern JavaScript engines. That case is the use of arguments.callee .

In the above code, foo can no longer be a subject to inlining since it needs to know about both itself and its caller. This not only defeats possible performance gains that would arise from inlining, but it also breaks encapsulation because the function may now be dependent on a specific calling context.

Making use of arguments.callee or any of its properties is highly discouraged .

Constructors

Constructors in JavaScript are yet again different from many other languages. Any function call that is preceded by the new keyword acts as a constructor.

Inside the constructor - the called function - the value of this refers to a newly created object. The prototype of this new object is set to the prototype of the function object that was invoked as the constructor.

If the function that was called has no explicit return statement, then it implicitly returns the value of this - the new object.

The above calls Person as constructor and sets the prototype of the newly created object to Person.prototype .

In case of an explicit return statement, the function returns the value specified by that statement, but only if the return value is an Object .

When the new keyword is omitted, the function will not return a new object.

While the above example might still appear to work in some cases, due to the workings of this in JavaScript, it will use the global object as the value of this .

In order to be able to omit the new keyword, the constructor function has to explicitly return a value.

Both calls to Robot return the same thing, a newly created object that has a property called getColor , which is a Closure .

It should also be noted that the call new Robot() does not affect the prototype of the returned object. While the prototype will be set on the newly created object, Robot never returns that new object.

In the above example, there is no functional difference between using and not using the new keyword.

Creating New Objects via Factories

It is often recommended to not use new because forgetting its use may lead to bugs.

In order to create a new object, one should rather use a factory and construct a new object inside of that factory.

While the above is robust against a missing new keyword and certainly makes the use of private variables easier, it comes with some downsides.

  • It uses more memory since the created objects do not share the methods on a prototype.
  • In order to inherit, the factory needs to copy all the methods from another object or put that object on the prototype of the new object.
  • Dropping the prototype chain just because of a left out new keyword is contrary to the spirit of the language.

While omitting the new keyword might lead to bugs, it is certainly not a reason to drop the use of prototypes altogether. In the end it comes down to which solution is better suited for the needs of the application. It is especially important to choose a specific style of object creation and use it consistently .

Scopes and Namespaces

Although JavaScript deals fine with the syntax of two matching curly braces for blocks, it does not support block scope; hence, all that is left in the language is function scope .

There are also no distinct namespaces in JavaScript, which means that everything gets defined in one globally shared namespace.

Each time a variable is referenced, JavaScript will traverse upwards through all the scopes until it finds it. In the case that it reaches the global scope and still has not found the requested name, it will raise a ReferenceError .

The Bane of Global Variables

The above two scripts do not have the same effect. Script A defines a variable called foo in the global scope, and script B defines a foo in the current scope.

Again, that is not at all the same effect : not using var can have major implications.

Leaving out the var statement inside the function test will override the value of foo . While this might not seem like a big deal at first, having thousands of lines of JavaScript and not using var will introduce horrible, hard-to-track-down bugs.

The outer loop will terminate after the first call to subLoop , since subLoop overwrites the global value of i . Using a var for the second for loop would have easily avoided this error. The var statement should never be left out unless the desired effect is to affect the outer scope.

Local Variables

The only source for local variables in JavaScript are function parameters and variables declared via the var statement.

While foo and i are local variables inside the scope of the function test , the assignment of bar will override the global variable with the same name.

JavaScript hoists declarations. This means that both var statements and function declarations will be moved to the top of their enclosing scope.

The above code gets transformed before execution starts. JavaScript moves the var statements, as well as function declarations, to the top of the nearest surrounding scope.

Missing block scoping will not only move var statements out of loops and their bodies, it will also make the results of certain if constructs non-intuitive.

In the original code, although the if statement seemed to modify the global variable goo , it actually modifies the local variable - after hoisting has been applied.

Without knowledge of hoisting , one might suspect the code below would raise a ReferenceError .

But of course, this works due to the fact that the var statement is being moved to the top of the global scope .

Name Resolution Order

All scopes in JavaScript, including the global scope , have the special name this , defined in them, which refers to the current object .

Function scopes also have the name arguments , defined in them, which contains the arguments that were passed to the function.

For example, when trying to access a variable named foo inside the scope of a function, JavaScript will look up the name in the following order:

  • In case there is a var foo statement in the current scope, use that.
  • If one of the function parameters is named foo , use that.
  • If the function itself is called foo , use that.
  • Go to the next outer scope, and start with #1 again.

A common problem associated with having only one global namespace is the likelihood of running into problems where variable names clash. In JavaScript, this problem can easily be avoided with the help of anonymous wrappers .

Unnamed functions are considered expressions ; so in order to be callable, they must first be evaluated.

There are other ways to evaluate and directly call the function expression which, while different in syntax, behave the same way.

It is recommended to always use an anonymous wrapper to encapsulate code in its own namespace. This does not only protect code against name clashes, but it also allows for better modularization of programs.

Additionally, the use of global variables is considered bad practice . Any use of them indicates badly written code that is prone to errors and hard to maintain.

Array Iteration and Properties

Although arrays in JavaScript are objects, there are no good reasons to use the for in loop. In fact, there are a number of good reasons against the use of for in on arrays.

Because the for in loop enumerates all the properties that are on the prototype chain and because the only way to exclude those properties is to use hasOwnProperty , it is already up to twenty times slower than a normal for loop.

In order to achieve the best performance when iterating over arrays, it is best to use the classic for loop.

There is one extra catch in the above example, which is the caching of the length of the array via l = list.length .

Although the length property is defined on the array itself, there is still an overhead for doing the lookup on each iteration of the loop. And while recent JavaScript engines may apply optimization in this case, there is no way of telling whether the code will run on one of these newer engines or not.

In fact, leaving out the caching may result in the loop being only half as fast as with the cached length.

The length Property

While the getter of the length property simply returns the number of elements that are contained in the array, the setter can be used to truncate the array.

Assigning a smaller length truncates the array. Increasing it creates a sparse array.

For the best performance, it is recommended to always use the plain for loop and cache the length property. The use of for in on an array is a sign of badly written code that is prone to bugs and bad performance.

The Array Constructor

Since the Array constructor is ambiguous in how it deals with its parameters, it is highly recommended to use the array literal - [] notation - when creating new arrays.

In cases when there is only one argument passed to the Array constructor and when that argument is a Number , the constructor will return a new sparse array with the length property set to the value of the argument. It should be noted that only the length property of the new array will be set this way; the actual indexes of the array will not be initialized.

Being able to set the length of the array in advance is only useful in a few cases, like repeating a string, in which it avoids the use of a loop.

Literals are preferred to the Array constructor. They are shorter, have a clearer syntax, and increase code readability.

Equality and Comparisons

JavaScript has two different ways of comparing the values of objects for equality.

The Equality Operator

The equality operator consists of two equal signs: ==

JavaScript features weak typing . This means that the equality operator coerces types in order to compare them.

The above table shows the results of the type coercion, and it is the main reason why the use of == is widely regarded as bad practice. It introduces hard-to-track-down bugs due to its complicated conversion rules.

Additionally, there is also a performance impact when type coercion is in play; for example, a string has to be converted to a number before it can be compared to another number.

The Strict Equality Operator

The strict equality operator consists of three equal signs: === .

It works like the normal equality operator, except that strict equality operator does not perform type coercion between its operands.

The above results are a lot clearer and allow for early breakage of code. This hardens code to a certain degree and also gives performance improvements in case the operands are of different types.

Comparing Objects

While both == and === are called equality operators, they behave differently when at least one of their operands is an Object .

Here, both operators compare for identity and not equality; that is, they will compare for the same instance of the object, much like is in Python and pointer comparison in C.

It is highly recommended to only use the strict equality operator. In cases where types need to be coerced, it should be done explicitly and not left to the language's complicated coercion rules.

The typeof Operator

The typeof operator (together with instanceof ) is probably the biggest design flaw of JavaScript, as it is almost completely broken .

Although instanceof still has limited uses, typeof really has only one practical use case, which does not happen to be checking the type of an object.

The JavaScript Type Table

In the above table, Type refers to the value that the typeof operator returns. As can be clearly seen, this value is anything but consistent.

The Class refers to the value of the internal [[Class]] property of an object.

The Class of an Object

The only way to determine an object's [[Class]] value is using Object.prototype.toString . It returns a string in the following format: '[object ' + valueOfClass + ']' , e.g [object String] or [object Array] :

In the above example, Object.prototype.toString gets called with the value of this being set to the object whose [[Class]] value should be retrieved.

Testing for Undefined Variables

The above will check whether foo was actually declared or not; just referencing it would result in a ReferenceError . This is the only thing typeof is actually useful for.

In order to check the type of an object, it is highly recommended to use Object.prototype.toString because this is the only reliable way of doing so. As shown in the above type table, some return values of typeof are not defined in the specification; thus, they can differ between implementations.

Unless checking whether a variable is defined, typeof should be avoided.

The instanceof Operator

The instanceof operator compares the constructors of its two operands. It is only useful when comparing custom made objects. Used on built-in types, it is nearly as useless as the typeof operator .

Comparing Custom Objects

Using instanceof with native types.

One important thing to note here is that instanceof does not work on objects that originate from different JavaScript contexts (e.g. different documents in a web browser), since their constructors will not be the exact same object.

The instanceof operator should only be used when dealing with custom made objects that originate from the same JavaScript context. Just like the typeof operator, every other use of it should be avoided .

Type Casting

JavaScript is a weakly typed language, so it will apply type coercion wherever possible.

To avoid the issues above, use of the strict equal operator is highly recommended. Although this avoids a lot of common pitfalls, there are still many further issues that arise from JavaScript's weak typing system.

Constructors of Built-In Types

The constructors of the built in types like Number and String behave differently when being used with the new keyword and without it.

Using a built-in type like Number as a constructor will create a new Number object, but leaving out the new keyword will make the Number function behave like a converter.

In addition, passing literals or non-object values will result in even more type coercion.

The best option is to cast to one of the three possible types explicitly .

Casting to a String

By prepending an empty string, a value can easily be cast to a string.

Casting to a Number

Using the unary plus operator, it is possible to cast to a number.

Casting to a Boolean

By using the not operator twice, a value can be converted to a boolean.

Why Not to Use eval

The eval function will execute a string of JavaScript code in the local scope.

However, eval only executes in the local scope when it is being called directly and when the name of the called function is actually eval .

The use of eval should be avoided. 99.9% of its "uses" can be achieved without it.

eval in Disguise

The timeout functions setTimeout and setInterval can both take a string as their first argument. This string will always get executed in the global scope since eval is not being called directly in that case.

Security Issues

eval also is a security problem, because it executes any code given to it. It should never be used with strings of unknown or untrusted origins.

eval should never be used. Any code that makes use of it should be questioned in its workings, performance and security. If something requires eval in order to work, it should not be used in the first place. A better design should be used, that does not require the use of eval .

undefined and null

JavaScript has two distinct values for nothing, null and undefined , with the latter being more useful.

The Value undefined

undefined is a type with exactly one value: undefined .

The language also defines a global variable that has the value of undefined ; this variable is also called undefined . However, this variable is neither a constant nor a keyword of the language. This means that its value can be easily overwritten.

Here are some examples of when the value undefined is returned:

  • Accessing the (unmodified) global variable undefined .
  • Accessing a declared but not yet initialized variable.
  • Implicit returns of functions due to missing return statements.
  • return statements that do not explicitly return anything.
  • Lookups of non-existent properties.
  • Function parameters that do not have any explicit value passed.
  • Anything that has been set to the value of undefined .
  • Any expression in the form of void(expression)

Handling Changes to the Value of undefined

Since the global variable undefined only holds a copy of the actual value of undefined , assigning a new value to it does not change the value of the type undefined .

Still, in order to compare something against the value of undefined , it is necessary to retrieve the value of undefined first.

To protect code against a possible overwritten undefined variable, a common technique used is to add an additional parameter to an anonymous wrapper that gets no argument passed to it.

Another way to achieve the same effect would be to use a declaration inside the wrapper.

The only difference here is that this version results in 4 more bytes being used in case it is minified, and there is no other var statement inside the anonymous wrapper.

Uses of null

While undefined in the context of the JavaScript language is mostly used in the sense of a traditional null , the actual null (both a literal and a type) is more or less just another data type.

It is used in some JavaScript internals (like declaring the end of the prototype chain by setting Foo.prototype = null ), but in almost all cases, it can be replaced by undefined .

Automatic Semicolon Insertion

Although JavaScript has C style syntax, it does not enforce the use of semicolons in the source code, so it is possible to omit them.

JavaScript is not a semicolon-less language. In fact, it needs the semicolons in order to understand the source code. Therefore, the JavaScript parser automatically inserts them whenever it encounters a parse error due to a missing semicolon.

Insertion happens, and the parser tries again.

The automatic insertion of semicolon is considered to be one of biggest design flaws in the language because it can change the behavior of code.

How it Works

The code below has no semicolons in it, so it is up to the parser to decide where to insert them.

Below is the result of the parser's "guessing" game.

The parser drastically changed the behavior of the code above. In certain cases, it does the wrong thing .

Leading Parenthesis

In case of a leading parenthesis, the parser will not insert a semicolon.

This code gets transformed into one line.

Chances are very high that log does not return a function; therefore, the above will yield a TypeError stating that undefined is not a function .

It is highly recommended to never omit semicolons. It is also recommended that braces be kept on the same line as their corresponding statements and to never omit them for single-line if / else statements. These measures will not only improve the consistency of the code, but they will also prevent the JavaScript parser from changing code behavior.

The delete Operator

In short, it's impossible to delete global variables, functions and some other stuff in JavaScript which have a DontDelete attribute set.

Global code and Function code

When a variable or a function is defined in a global or a function scope it is a property of either the Activation object or the Global object. Such properties have a set of attributes, one of which is DontDelete . Variable and function declarations in global and function code always create properties with DontDelete , and therefore cannot be deleted.

Explicit properties

Explicitly set properties can be deleted normally.

In the example above, obj.x and obj.y can be deleted because they have no DontDelete attribute. That's why the example below works too.

Here we use a trick to delete a . this here refers to the Global object and we explicitly declare variable a as its property which allows us to delete it.

IE (at least 6-8) has some bugs, so the code above doesn't work.

Function arguments and built-ins

Functions' normal arguments, arguments objects and built-in properties also have DontDelete set.

Host objects

The behaviour of delete operator can be unpredictable for hosted objects. Due to the specification, host objects are allowed to implement any kind of behavior.

In conclusion

The delete operator often has unexpected behaviour and can only be safely used to delete explicitly set properties on normal objects.

setTimeout and setInterval

Since JavaScript is asynchronous, it is possible to schedule the execution of a function using the setTimeout and setInterval functions.

When setTimeout is called, it returns the ID of the timeout and schedule foo to run approximately one thousand milliseconds in the future. foo will then be executed once .

Depending on the timer resolution of the JavaScript engine running the code, as well as the fact that JavaScript is single threaded and other code that gets executed might block the thread, it is by no means a safe bet that one will get the exact delay specified in the setTimeout call.

The function that was passed as the first parameter will get called by the global object , which means that this inside the called function refers to the global object.

Stacking Calls with setInterval

While setTimeout only runs the function once, setInterval - as the name suggests - will execute the function every X milliseconds, but its use is discouraged.

When code that is being executed blocks the timeout call, setInterval will still issue more calls to the specified function. This can, especially with small intervals, result in function calls stacking up.

In the above code, foo will get called once and will then block for one second.

While foo blocks the code, setInterval will still schedule further calls to it. Now, when foo has finished, there will already be ten further calls to it waiting for execution.

Dealing with Possible Blocking Code

The easiest solution, as well as most controllable solution, is to use setTimeout within the function itself.

Not only does this encapsulate the setTimeout call, but it also prevents the stacking of calls and gives additional control. foo itself can now decide whether it wants to run again or not.

Manually Clearing Timeouts

Clearing timeouts and intervals works by passing the respective ID to clearTimeout or clearInterval , depending on which set function was used in the first place.

Clearing All Timeouts

As there is no built-in method for clearing all timeouts and/or intervals, it is necessary to use brute force in order to achieve this functionality.

But there might still be timeouts that are unaffected by this arbitrary number. Another way of doing this is to consider that the ID given to a timeout is incremented by one every time you call setTimeout .

Even though this works on all major browsers today, it isn't specified that the IDs should be ordered that way and it may change. Therefore, it is instead recommended to keep track of all the timeout IDs, so they can be cleared specifically.

Hidden Use of eval

setTimeout and setInterval can also take a string as their first parameter. This feature should never be used because it internally makes use of eval .

Since eval is not getting called directly in this case, the string passed to setTimeout will be executed in the global scope ; thus, it will not use the local variable foo from the scope of bar .

It is further recommended to not use a string to pass arguments to the function that will get called by either of the timeout functions.

A string should never be used as the parameter of setTimeout or setInterval . It is a clear sign of really bad code, when arguments need to be supplied to the function that gets called. An anonymous function should be passed that then takes care of the actual call.

Furthermore, the use of setInterval should be avoided because its scheduler is not blocked by executing JavaScript.

  • New Sandbox Program

Click on one of our programs below to get started coding in the sandbox!

gardening in javascript assignment expert

Gardening 101

In this project, students will use event and animation techniques to create an animation of a plant growing through various stages of development.

High School

gardening in javascript assignment expert

Project Description

Project demo, project overview.

CodeHS Logo

  • Computer Science Curriculum
  • Certifications
  • Professional Development
  • Assignments
  • Classroom Management
  • Integrations
  • Course Catalog
  • Project Catalog
  • K-12 Pathways
  • State Courses
  • Spanish Courses
  • Hour of Code
  • Digital Textbooks
  • Online PD Courses
  • In-Person PD Workshops
  • Virtual PD Workshops
  • Free PD Workshops
  • Teacher Certification Prep
  • Microcredentials
  • PD Membership

Programming Languages

  • Case Studies
  • Testimonials
  • Read Write Code Blog
  • Read Write Code Book
  • Knowledge Base
  • Student Projects
  • Career Center
  • Privacy Center
  • Privacy Policy
  • Accessibility
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • JavaScript Arithmetic Unary Negation(-) Operator
  • JavaScript Pipeline Operator
  • JavaScript Instanceof Operator
  • JavaScript Arithmetic Unary Plus(+) Operator
  • JavaScript Remainder(%) Operator
  • Operator precedence in JavaScript
  • What does !== undefined mean in JavaScript ?
  • JavaScript Comparison Operators
  • JavaScript in Operator
  • JavaScript Arithmetic Operators
  • JavaScript Ternary Operator
  • JavaScript Comma Operator
  • JavaScript Remainder Assignment(%=) Operator
  • How to get negative result using modulo operator in JavaScript ?
  • What is (~~) "double tilde" operator in JavaScript ?
  • How to access object properties from result returned by async() function in JavaScript ?
  • What does OR Operator || in a Statement in JavaScript ?
  • What is JavaScript >>> Operator and how to use it ?
  • Explain the purpose of the ‘in’ operator in JavaScript

JavaScript Assignment Operators

A ssignment operators.

Assignment operators are used to assign values to variables in JavaScript.

Assignment Operators List

There are so many assignment operators as shown in the table with the description.

Below we have described each operator with an example code:

Addition assignment operator(+=).

The Addition assignment operator adds the value to the right operand to a variable and assigns the result to the variable. Addition or concatenation is possible. In case of concatenation then we use the string as an operand.

Subtraction Assignment Operator(-=)

The Substraction Assignment Operator subtracts the value of the right operand from a variable and assigns the result to the variable.

Multiplication Assignment Operator(*=)

The Multiplication Assignment operator multiplies a variable by the value of the right operand and assigns the result to the variable.

Division Assignment Operator(/=)

The Division Assignment operator divides a variable by the value of the right operand and assigns the result to the variable.

Remainder Assignment Operator(%=)

The Remainder Assignment Operator divides a variable by the value of the right operand and assigns the remainder to the variable.

Exponentiation Assignment Operator

The Exponentiation Assignment Operator raises the value of a variable to the power of the right operand.

Left Shift Assignment Operator(<<=)

This Left Shift Assignment O perator moves the specified amount of bits to the left and assigns the result to the variable.

Right Shift Assignment O perator(>>=)

The Right Shift Assignment Operator moves the specified amount of bits to the right and assigns the result to the variable.

Bitwise AND Assignment Operator(&=)

The Bitwise AND Assignment Operator uses the binary representation of both operands, does a bitwise AND operation on them, and assigns the result to the variable.

Btwise OR Assignment Operator(|=)

The Btwise OR Assignment Operator uses the binary representation of both operands, does a bitwise OR operation on them, and assigns the result to the variable.

Bitwise XOR Assignment Operator(^=)

The Bitwise XOR Assignment Operator uses the binary representation of both operands, does a bitwise XOR operation on them, and assigns the result to the variable.

Logical AND Assignment Operator(&&=)

The Logical AND Assignment assigns the value of  y  into  x  only if  x  is a  truthy  value.

Logical OR Assignment Operator( ||= )

The Logical OR Assignment Operator is used to assign the value of y to x if the value of x is falsy.

Nullish coalescing Assignment Operator(??=)

The Nullish coalescing Assignment Operator assigns the value of y to x if the value of x is null.

Supported Browsers: The browsers supported by all JavaScript Assignment operators are listed below:

  • Google Chrome
  • Microsoft Edge
  • Internet Explorer

Please Login to comment...

  • javascript-operators
  • Web Technologies
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • Otter AI vs Dragon Speech Recognition: Which is the best AI Transcription Tool?
  • Google Messages To Let You Send Multiple Photos
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Assignment (=)

The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .

An expression specifying the value to be assigned to x .

Return value

The value of y .

Thrown in strict mode if assigning to an identifier that is not declared in the scope.

Thrown in strict mode if assigning to a property that is not modifiable .

Description

The assignment operator is completely different from the equals ( = ) sign used as syntactic separators in other locations, which include:

  • Initializers of var , let , and const declarations
  • Default values of destructuring
  • Default parameters
  • Initializers of class fields

All these places accept an assignment expression on the right-hand side of the = , so if you have multiple equals signs chained together:

This is equivalent to:

Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:

Simple assignment and chaining

Value of assignment expressions.

The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.

Unqualified identifier assignment

The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .

Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:

So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.

In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.

Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

Assignment with destructuring

The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.

For more information, see Destructuring assignment .

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Assignment operators in the JS guide
  • Destructuring assignment

IMAGES

  1. Ozaria

    gardening in javascript assignment expert

  2. A book to learn type-driven development in JavaScript

    gardening in javascript assignment expert

  3. A book to learn type-driven development in JavaScript

    gardening in javascript assignment expert

  4. JavaScript Garden by Ivo Wetzel

    gardening in javascript assignment expert

  5. JavaScript Garden by Ivo Wetzel

    gardening in javascript assignment expert

  6. JavaScript Assignment Operators

    gardening in javascript assignment expert

VIDEO

  1. html css JavaScript , assignment #2 at islamia university of Bahawalpur

  2. Library Management||Coding Assignment

  3. Week 3 Javascript Assignment

COMMENTS

  1. Answer in Web Application for raj #231951 - Assignment Expert

    Question #231951. Gardening. We have a task to do Gardening. Given two boolean values. isGrassTrimmerFound and isWaterHosePipeFound as inputs, create three JS promises using async/await and try/catch blocks. For cutting the grass, resolve with "Grass Trimmed" text, if the isGrassTrimmerFound is true. reject with "Grass Trimmer Not Found" text ...

  2. garden · GitHub Topics · GitHub

    This Javascript app allows the user to “plant” a digital version of a small garden to help keep track of what's growing, and how to care for it. javascript plants garden html-css-javascript Updated Jun 25, 2021

  3. gardening · GitHub Topics · GitHub

    Add this topic to your repo. To associate your repository with the gardening topic, visit your repo's landing page and select "manage topics." GitHub is where people build software. More than 100 million people use GitHub to discover, fork, and contribute to over 420 million projects.

  4. GitHub - jillbowen/garden_planner_frontend: This Javascript ...

    This single page Javascript app allows you to create a digital version of your garden to help you keep track of what's growing, and how to care for it. NOTE: This app is meant for small container gardening, so each garden comfortably holds 6 plants. Happy gardening!

  5. JavaScript Garden - GitHub Pages

    JavaScript Garden is a growing collection of documentation about the most quirky parts of the JavaScript programming language. It gives advice to avoid common mistakes and subtle bugs, as well as performance issues and bad practices, that non-expert JavaScript programmers may encounter on their endeavours into the depths of the language.

  6. Gardening 101 | CodeHS

    In this project, you are going to use CodeHS graphics to animate a few stages of plant growth. With a timer, you’ll be able to keep track of “time” passing and use that information to move through different parts of a plant’s development. In the demo below ( click to plant a seed ), you can see three distinct stages: The seed is planted ...

  7. JavaScript Assignment Operators - GeeksforGeeks

    Assignment Operators. Assignment operators are used to assign values to variables in JavaScript. Syntax: data=value. Example: // Lets take some variablesx=10y=20x=y // Here, x is equal to 20y=x // Here, y is equal to 10.

  8. Assignment (=) - JavaScript | MDN - MDN Web Docs

    Assignment (=) The assignment ( =) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.