JavaScript is a client-side programming language. It is used in over 90% of the websites in the world. It is one of the most used programming languages in the world. So, today we will be talking about the 10 most asked questions about JavaScript. 10 Most Asked Questions About JavaScript 1. How to remove a specific item from an array? Answer: First, find the of the array element you want to remove using , and then remove that index with . index indexOf splice The splice() method changes the contents of an array by removing existing elements and/or adding new elements. array = [ , , ]; .log(array); index = array.indexOf( ); (index > ) { array.splice(index, ); } .log(array); const 2 5 9 console const 5 if -1 1 // array = [2, 9] console The second parameter of is the number of elements to remove. Note that modifies the array in place and returns a new array containing the elements that have been removed. splice splice For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of from ), while the second function removes all occurrences: 5 [2,5,9,1,5,8,5] { index = arr.indexOf(value); (index > ) { arr.splice(index, ); } arr; } { i = ; (i < arr.length) { (arr[i] === value) { arr.splice(i, ); } { ++i; } } arr; } ( ) function removeItemOnce arr, value var if -1 1 return ( ) function removeItemAll arr, value var 0 while if 1 else return Alternative Answer: To remove an element of an array at an index : i array.splice(i, ); 1 If you want to remove every element with value from the array: number ( i = array.length - ; i >= ; i--) { (array[i] === number) { array.splice(i, ); } } for var 1 0 if 1 If you just want to make the element at index no longer exist, but you don’t want the indexes of the other elements to change: i array[i]; delete 2. How to redirect the user from one page to another using jQuery or pure JavaScript? Answer: One does not simply redirect using jQuery. jQuery is not necessary, and will best simulate an HTTP redirect. window.location.replace(...) is better than using , because does not keep the originating page in the session history, meaning the user won’t get stuck in a never-ending back-button fiasco. window.location.replace(...) window.location.href replace() If you want to simulate someone clicking on a link, use location.href If you want to simulate an HTTP redirect, use location.replace For example: .location.replace( ); .location.href = ; // similar behavior as an HTTP redirect window "http://stackoverflow.com" // similar behavior as clicking on a link window "http://stackoverflow.com" Alternative Answer: You can also do it as shown below. $(location).attr( , ) 'href' 'http://stackoverflow.com' 3. How do JavaScript closures work? Answer: A closure is a pairing of: A function, and A reference to that function’s outer scope (lexical environment) A lexical environment is part of every execution context (stack frame), and is a map between identifiers (ie. local variable names) and values. Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to “see” variables declared outside the function, regardless of when and where the function is called. If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain. In the following code, forms a closure with the lexical environment of the execution context created when is invoked, variable : inner foo closing over secret { secret = .trunc( .random()* ) { .log( ) } } f = foo() f() ( ) function foo const Math Math 100 return ( ) function inner console `The secret number is .` ${secret} const // `secret` is not directly accessible from outside `foo` // The only way to retrieve `secret`, is to invoke `f` In other words, in JavaScript, functions carry a reference to a private “box of state”, to which only they (and any other functions declared within the same lexical environment) have access. This box of state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation. And remember functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++. If JavaScript did not have closures, then more state would have to be passed between functions , making parameter lists longer and code noisier. explicitly So, if you want a function to always have access to a private piece of state, you can use a closure, and frequently we do want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating state with functionality. In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, remains available to the function object , it has been returned from . secret inner after foo Uses of Closures Closures are useful whenever you need a private state associated with a function. This is a very common scenario and you need to remember that JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need. Private Instance Variables In the following code, function closes over the details of the car. toString { { toString() { } } } car = Car( , , , ) .log(car.toString()) ( ) function Car manufacturer, model, year, color return return ` ( , )` ${manufacturer} ${model} ${year} ${color} const new 'Aston Martin' 'V8 Vantage' '2012' 'Quantum Silver' console Functional Programming In the following code, function closes over both and . inner fn args { args = [] { (args.length === fn.length) fn(...args) args.push(arg) inner } } { a + b } curriedAdd = curry(add) .log(curriedAdd( )( )()) ( ) function curry fn const return ( ) function inner arg if return return ( ) function add a, b return const console 2 3 // 5 Event-Oriented Programming In the following code, function closes over variable . onClick BACKGROUND_COLOR $ = .querySelector.bind( ) BACKGROUND_COLOR = { $( ).style.background = BACKGROUND_COLOR } $( ).addEventListener( , onClick) const document document const 'rgba(200,200,242,1)' ( ) function onClick 'body' 'button' 'click' <button> background color< Set /button> Modularization In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions and close over the private state and functions, they need to complete their work. Closures have enabled us to modularise and encapsulate our code. tick toString namespace = {}; ( { numbers = [] { .trunc(n) } { numbers.push( .random() * ) } { numbers.map(format) } n.counter = { tick, toString } }(namespace)) counter = namespace.counter counter.tick() counter.tick() .log(counter.toString()) let ( ) function foo n let ( ) function format n return Math ( ) function tick Math 100 ( ) function toString return const console Examples Example 1 This example shows that the local variables are not copied in the closure. The closure maintains a reference to the original variables . It is as though the stack-frame stays alive in memory even after the outer function exits. themselves { x = inner = { .log(x) } x = x+ inner } f = foo() f() ( ) function foo let 42 let ( ) function console 1 return var // logs 43 Example 2 In the following code, three methods , and all close over the same lexical environment. log increment update And every time is called, a new execution context (stack frame) is created and a completely new variable , and a new set of functions ( etc.) are created, that close over this new variable. createObject x log { x = ; { log() { .log(x) }, increment() { x++ }, update(value) { x = value } } } o = createObject() o.increment() o.log() o.update( ) o.log() p = createObject() p.log() ( ) function createObject let 42 return console const // 43 5 // 5 const // 42 Example 3 If you are using variables declared using , be careful you understand which variable you are closing over. Variables declared using are hoisted. This is much less of a problem in modern JavaScript due to the introduction of and . var var let const In the following code, each time around the loop, a new function is created, which closes over . But because is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of (3) is printed, three times. inner i var i i { result = [] ( i = ; i < ; i++) { result.push( { .log(i) } ) } result } result = foo() ( i = ; i < ; i++) { result[i]() } ( ) function foo var for var 0 3 ( ) function inner console return const // The following will print `3`, three times... for var 0 3 Final points: Whenever a function is declared in JavaScript, a closure is created. Returning a from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution. function Whenever you use inside a function, a closure is used. The text you eval can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using . eval() eval('var foo = …') When you use (the ) inside a function, it does not close over its lexical environment, it closes over the global context instead. The new function cannot reference the local variables of the outer function. new Function(…) Function constructor A closure in JavaScript is like keeping a reference ( a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain. not A closure is created when a function is declared. This closure is used to configure the execution context when the function is invoked. A new set of local variables is created every time a function is called. Alternative Answer: Every function in JavaScript maintains a link to its outer lexical environment. A lexical environment is a map of all the names (eg. variables, parameters) within scope, with their values. So, whenever you see the keyword, code inside that function has access to variables declared outside the function. function { tmp = ; { .log(x + y + (++tmp)); } bar( ); } foo( ); ( ) function foo x var 3 ( ) function bar y console // will log 16 10 2 This will log because function closes over the parameter and the variable , both of which exist in the lexical environment of the outer function . 16 bar x tmp foo Function , together with its link with the lexical environment of function is a closure. bar foo A function doesn’t have to in order to create a closure. Simply by virtue of its declaration, every function closes over its enclosing lexical environment, forming a closure. return { tmp = ; { .log(x + y + (++tmp)); } } bar = foo( ); bar( ); bar( ); ( ) function foo x var 3 return ( ) function y console // will also log 16 var 2 10 // 16 10 // 17 The above function will also log 16 because the code inside can still refer to the argument and variable , even though they are no longer directly in scope. bar x tmp However, since is still hanging around inside ‘s closure, it is available to be incremented. It will be incremented each time you call . tmp bar bar The simplest example of a closure is this: a = ; { .log(a); .log(b); } b = ; test(); var 10 ( ) function test console // will output 10 console // will output 6 var 6 When a JavaScript function is invoked, a new execution context is created. Together with the function arguments and the target object, this execution context also receives a link to the lexical environment of the calling execution context, meaning the variables declared in the outer lexical environment (in the above example, both and ) are available from . ec a b ec Every function creates a closure because every function has a link to its outer lexical environment. Note that variables are visible from within a closure, copies. themselves not 4. What does “use strict” do in JavaScript, and what is the reasoning behind it? To quote some interesting parts: Answer: Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This strict context prevents certain actions from being taken and throws more exceptions. And Strict mode helps out in a couple of ways: It catches some common coding bloopers, throwing exceptions. It prevents or throws errors when relatively “unsafe” actions are taken (such as gaining access to the global object). It disables features that are confusing or poorly thought out. Also, note that you can apply “strict mode” to the whole file or you can use it only for a specific function . ( { ; })(); // Non-strict code... ( ) function "use strict" // Define your library strictly... // Non-strict code... Which might be helpful if you have to mix old and new code. So, it’s a bit like the you can use in Perl. It helps you make fewer errors, by detecting more things that could lead to breakages. "use strict" Strict mode is now . supported by all major browsers Inside (with and statements) and , strict mode is always enabled and cannot be disabled. native ECMAScript modules import export ES6 classes Alternative Answer: It’s a new feature of ECMAScript 5. It’s just a string you put in your JavaScript files (either at the top of your file or inside of a function) that looks like this: ; "use strict" Putting it in your code now shouldn’t cause any problems with current browsers as it’s just a string. It may cause problems with your code in the future if your code violates the pragma. For instance, if you currently have without defining first, your code will start failing which is a good thing in our opinion. foo = "bar" foo 5. How to check whether a string contains a substring in JavaScript? ECMAScript 6 introduced : Answer: String.prototype.includes string = ; substring = ; .log(string.includes(substring)); const "foo" const "oo" console , though. In CMAScript 5 or older environments, use , which returns -1 when a substring cannot be found: includes doesn’t have Internet Explorer support String.prototype.indexOf string = ; substring = ; .log(string.indexOf(substring) !== ); var "foo" var "oo" console -1 Alternative Answer: : There is a String.prototype.includes in ES6 .includes( ); > "potato" "to" true Note that this with no or incomplete ES6 support. To make it work in old browsers, you may wish to use a transpiler like , a shim library like , or this : does not work in Internet Explorer or some other old browsers Babel es6-shim polyfill from MDN (! .prototype.includes) { .prototype.includes = { ; ( start !== ) { start = ; } (start + search.length > .length) { ; } { .indexOf(search, start) !== ; } }; } if String String ( ) function search, start 'use strict' if typeof 'number' 0 if this return false else return this -1 6. var functionName = function() {} vs function functionName() {} The difference is that is a function expression and so only defined when that line is reached, whereas is a function declaration and is defined as soon as its surrounding function or script is executed (due to ). Answer: functionOne functionTwo hoisting For example, a function expression: functionOne(); functionOne = { .log( ); }; // TypeError: functionOne is not a function var ( ) function console "Hello!" And, a function declaration: functionTwo(); { .log( ); } // Outputs: "Hello!" ( ) function functionTwo console "Hello!" Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block. ; { { .log( ); } } functionThree(); 'use strict' // note this block! ( ) function functionThree console "Hello!" // ReferenceError Alternative Answer: is scoped too — the name is defined in the scope where this definition is encountered. Example: function abc(){} abc { {}; } ( ) function xyz ( ) function abc // abc is defined here... // ...but not here Secondly, it is possible to combine both styles: { {}; } ( ) function xyz ( ) function abc // abc is defined here... // ...but not here is going to be defined, as usual, abc is undefined in all browsers but Internet Explorer does not rely on it being defined. But it will be defined inside its body: xyz xyz = { } var ( ) function abc // xyz is visible here // abc is visible here // xyz is visible here // abc is undefined here If you want to alias functions on all browsers, use this kind of declaration: {}; xyz = abc; ( ) function abc var In this case, both and are aliases of the same object: xyz abc .log(xyz === abc); console // prints "true" One compelling reason to use the combined style is the “name” attribute of function objects ( ). Basically when you define a function like not supported by Internet Explorer .log(xyz === abc); console // prints "true" its name is automatically assigned. But when you define it like abc = {}; .log(abc.name); var ( ) function console // prints "" its name is empty — we created an anonymous function and assigned it to some variable. Another good reason to use the combined style is to use a short internal name to refer to itself while providing a long non-conflicting name for external users: really.long.external.scoped.name = { shortcut(n - ); someFunction(shortcut); } // Assume really.long.external.scoped is {} ( ) function shortcut n // Let it call itself recursively: 1 // ... // Let it pass itself as a callback: // ... In the example above we can do the same with an external name, but it’ll be too unwieldy (and slower). (Another way to refer to itself is to use arguments.callee , which is still relatively long, and not supported in the strict mode.) Deep down, JavaScript treats both statements differently. This is a function declaration: {} ( ) function abc here is defined everywhere in the current scope: abc abc(); {} abc(); // We can call it here // Works // Yet, it is defined down there. ( ) function abc // We can call it again // Works Also, it hoisted through a statement: return abc(); ; {} // We can call it here // Works return ( ) function abc This is a function expression: xyz = {}; var ( ) function here is defined from the point of assignment: xyz xyz(); xyz = {} xyz(); // We can't call it here // UNDEFINED!!! // Now it is defined ( ) function // We can call it here // works Function declaration vs. function expression is the real reason why there is a difference. Fun fact: xyz = {}; .log(xyz.name); var ( ) function abc console // Prints "abc" Personally, we prefer the “function expression” declaration because this way we can control the visibility. When we define the function like abc = {}; var ( ) function We know that we defined the function locally. When we define the function like abc = {}; var ( ) function We know that we defined it globally providing that we didn’t define anywhere in the chain of scopes. This style of the definition is resilient even when used inside . While the definition abc eval() {}; ( ) function abc depends on the context and may leave you guessing where it is actually defined, especially in the case of — the answer is it depends on the browser. eval() 7. How to remove a property from a JavaScript object? You can do as shown below: Answer: myObject.regex; myObject[ ]; prop = ; myObject[prop]; delete // or, delete 'regex' // or, var "regex" delete Demo myObject = { : , : , : }; myObject.regex; .log(myObject); var "ircEvent" "PRIVMSG" "method" "newURI" "regex" "^http://.*" delete console Alternative Answer: Objects in JavaScript can be thought of as maps between keys and values. The operator is used to remove these keys, more commonly known as object properties, one at a time. delete obj = { : } .log(obj.hasOwnProperty( )) obj.myProperty .log(obj.hasOwnProperty( )) var myProperty 1 console 'myProperty' // true delete console 'myProperty' // false The operator does not directly free memory, and it differs from simply assigning the value of or to a property, in that, the property is removed from the object. Note that if the of a deleted property was a reference type (an object), and another part of your program still holds a reference to that object, then that object will, of course, not be garbage collected until all references to it have disappeared. delete null undefined itself value will only work on properties whose descriptor marks them as configurable. delete 8. Which equals operator (== vs ===) should be used in JavaScript comparisons? Answer: The strict equality operator ( ) behaves identically to the abstract equality operator ( ) except no type conversion is done, and the types must be the same to be considered equal. === == Reference: Javascript Tutorial: Comparison Operators The operator will compare for equality . The operator will do the conversion, so if two values are not the same type will simply return . Both are equally quick. == after doing any necessary type conversions === not === false JavaScript has two sets of equality operators: and , and their evil twins and . The good ones work the way you would expect. If the two operands are of the same type and have the same value, then produces and produces false. === !== == != === true !== The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. The rules by which they do that are complicated and unmemorable. These are some of the interesting cases: == == == == == == == == == '' '0' // false 0 '' // true 0 '0' // true false 'false' // false false '0' // true false undefined // false false null // false null undefined // true ' \t\r\n ' 0 // true The lack of transitivity is alarming. Our advice is to never use the evil twins. Instead, always use and . === !== All of the comparisons just shown produce false with the operator. === For reference types and act consistently with one another (except in a special case). == === a = [ , , ]; b = [ , , ]; c = { : , : }; d = { : , : }; e = ; f = + ; a == b a === b c == d c === d e == f e === f var 1 2 3 var 1 2 3 var x 1 y 2 var x 1 y 2 var "text" var "te" "xt" // false // false // false // false // true // true The special case is when you compare a literal with an object that valuates to the same literal, due to its or method. toString valueOf For example, consider the comparison of a string literal with a string object created by the constructor. String == ( ) === ( ) "abc" new String "abc" // true "abc" new String "abc" // false Here the operator is checking the values of the two objects and returning , but the is seeing that they’re not the same type and returning . Which one is correct? That really depends on what you’re trying to compare. == true === false Our advice is to bypass the question entirely and just don’t use the constructor to create string objects. String Alternative Answer: Using the operator ( ) == Equality == ; == ; true 1 //true, because 'true' is converted to 1 and then compared "2" 2 //true, because "2" is converted to 2 and then compared Using the operator ( ) === Identity === ; === ; true 1 //false "2" 2 //false This is because the , meaning that the interpreter implicitly tries to convert the values before comparing. equality operator == does type coercion On the other hand, the , and thus does not convert the values when comparing, and is, therefore, faster (as according to test) as it skips one step. identity operator === does not do type coercion This JS benchmark 9. What is the most efficient way to deep clone an object in JavaScript? Answer: Native deep cloning It’s called “structured cloning”, works experimentally in Node 11 and later, and hopefully will land in browsers. Fast cloning with data loss – JSON.parse/stringify If you do not use s, functions, , , RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object, a very simple one-liner to deep clone an object is: Date undefined Infinity JSON.parse(JSON.stringify(object)) a = { : , : , : , : , : (), undef: , inf: , re: , } .log(a); .log( a.date); clone = .parse( .stringify(a)); .log(clone); .log( clone.date); const string 'string' number 123 bool false nul null date new Date // stringified undefined // lost Infinity // forced to 'null' /.*/ // lost console console typeof // Date object const JSON JSON console console typeof // result of .toISOString() Reliable cloning using a library Since cloning objects is not trivial (complex types, circular references, function, etc.), most major libraries provide a function to clone objects. – if you’re already using a library, check if it has an object cloning function. For example, Don’t reinvent the wheel lodash – ; can be imported separately via the module and is probably your best choice if you’re not already using a library that provides a deep cloning function cloneDeep lodash.clonedeep AngularJS – angular.copy jQuery – ; only clones DOM elements jQuery.extend(true, { }, oldObject) .clone() ES6 For completeness, note that ES6 offers two shallow copy mechanisms: and the . which copies values of all enumerable own properties from one object to another. For example: Object.assign() spread syntax A1 = { : }; A2 = .assign({}, A1); A3 = {...A1}; var a "2" var Object var // Spread Syntax Alternative Answer: Check out this benchmark: http://jsben.ch/#/bWfk9 In our previous tests where speed was a main concern we found .parse( .stringify(obj)) JSON JSON to be the slowest way to deep clone an object (it is slower than with flag set true by 10-20%). jQuery.extend deep jQuery.extend is pretty fast when the flag is set to (shallow clone). It is a good option, because it includes some extra logic for type validation and doesn’t copy over undefined properties, etc., but this will also slow you down a little. deep false If you know the structure of the objects you are trying to clone or can avoid deep nested arrays you can write a simple loop to clone your object while checking hasOwnProperty and it will be much much faster than jQuery. for (var i in obj) Lastly if you are attempting to clone a known object structure in a hot loop you can get much much more performance by simply in-lining the cloning procedure and manually constructing the object. JavaScript trace engines suck at optimizing loops and checking hasOwnProperty will slow you down as well. Manual clone when speed is an absolute must. for..in clonedObject = { : obj.knownProp, .. } var knownProp Beware using the method on objects – returns a string representation of the date in ISO format, which convert back to a object. . JSON.parse(JSON.stringify(obj)) Date JSON.stringify(new Date()) JSON.parse() doesn’t Date See this answer for more details Additionally, please note that in Chrome 65 at least, native cloning is not the way to go. According to JSPerf, performing native cloning by creating a new function is nearly slower than using JSON.stringify which is incredibly fast all the way across the board. 800x Update for ES6 If you are using Javascript ES6 try this native method for cloning or shallow copy. .assign({}, obj); Object 10. How to include a JavaScript file in another JavaScript file? Answer: The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed. But since 2015 (ES6), JavaScript has had the standard to import modules in Node.js, which is also supported by . ES6 modules most modern browsers For compatibility with older browsers, build tools like and and/or transpilation tools like can be used. Webpack Rollup Babel ES6 Modules ECMAScript (ES6) modules have been since v8.5, with the flag, and since at least Node.js v13.8.0 without the flag. To enable “ESM” (vs. Node.js’s previous CommonJS-style module system [“CJS”]) you either use in or give the files the extension . (Similarly, modules written with Node.js’s previous CJS module can be named if your default is ESM.) supported in Node.js --experimental-modules "type": "module" package.json .mjs .cjs Using : package.json { : } "type" "module" Then : module.js { ; } export ( ) function hello return "Hello" Then : main.js { hello } ; val = hello(); import from './module.js' let // val is "Hello"; Using , you’d have : .mjs module.mjs { ; } export ( ) function hello return "Hello" Then : main.mjs { hello } ; val = hello(); import from './module.mjs' let // val is "Hello"; ECMAScript modules in browsers Browsers have had support for loading ECMAScript modules directly (no tools like Webpack required) Safari 10.1, Chrome 61, Firefox 60, and Edge 16. Check the current support at . There is no need to use Node.js’ extension; browsers completely ignore file extensions on modules/scripts. since caniuse .mjs <script type= > { hello } ; hello( ); "module" import from './hello.mjs' // Or it could be simply `hello.js` 'world' </ > script { div = .createElement( ); div.textContent = ; .body.appendChild(div); } // hello.mjs -- or it could be simply `hello.js` export ( ) function hello text const document 'div' `Hello ` ${text} document Read more at https://jakearchibald.com/2017/es-modules-in-browsers/ Dynamic imports in browsers Dynamic imports let the script load other scripts as needed: <script type= > ( ).then( { .hello( ); }); "module" import 'hello.mjs' => module module 'world' </ > script Read more at https://developers.google.com/web/updates/2017/11/dynamic-import Node.js require The older CJS module style, still widely used in Node.js, is the system. module.exports/require .exports = { : { ; } } // mymodule.js module hello ( ) function return "Hello" myModule = ( ); val = myModule.hello(); // server.js const require './mymodule' let // val is "Hello" There are other ways for JavaScript to include external JavaScript contents in browsers that do not require preprocessing. AJAX Loading You could load an additional script with an AJAX call and then use to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using also opens the door to bugs, hacks, and security issues. eval eval Fetch Loading Like Dynamic Imports, you can load one or many scripts with a call using promises to control order of execution for script dependencies using the library: fetch Fetch Inject fetchInject([ ]).then( { .log( ) }) 'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js' => () console `Finish in less than ` ${moment().endOf( ).fromNow( )} 'year' true jQuery Loading The library provides loading functionality : jQuery in one line $.getScript( , { alert( ); }); "my_lovely_script.js" ( ) function "Script loaded but not necessarily executed." Dynamic Script Loading You could add a script tag with the script URL into the HTML. To avoid the overhead of jQuery, this is an ideal solution. The script can even reside on a different server. Furthermore, the browser evaluates the code. The tag can be injected into either the web page , or inserted just before the closing tag. <script> <head> </body> Here is an example of how this could work: { script = .createElement( ); script.src = url; .head.appendChild(script); } ( ) function dynamicallyLoadScript url var document "script" // create a script DOM node // set its src to the provided URL document // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead) This function will add a new tag to the end of the head section of the page, where the attribute is set to the URL which is given to the function as the first parameter. <script> src Both of these solutions are discussed and illustrated in . JavaScript Madness: Dynamic Script Loading Detecting when the script has been executed Now, there is a big issue you must know about. Doing that implies that . Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance. (This applies to both the jQuery method and the manual dynamic script loading method.) you remotely load the code It means that if you use these tricks directly, , because it will be still loading. you won’t be able to use your newly loaded code the next line after you asked it to be loaded For example: contains : my_lovely_script.js MySuperObject js = .createElement( ); js.type = ; js.src = jsFilePath; .body.appendChild(js); s = MySuperObject(); : MySuperObject is var document "script" "text/javascript" document var new Error undefined Then you reload the page hitting . And it works! Confusing… F5 So what to do about it? You can put all the code using the remote library in the callback function. For example: { head = .head; script = .createElement( ); script.type = ; script.src = url; script.onreadystatechange = callback; script.onload = callback; head.appendChild(script); } ( ) function loadScript url, callback // Adding the script tag to the head as suggested before var document var document 'script' 'text/javascript' // Then bind the event to the callback function. // There are several events for cross browser compatibility. // Fire the loading Then you write the code you want to use after the script is loaded in a : lambda function myPrettyCode = { }; var ( ) function // Here, do whatever you want Then you run all that: loadScript( , myPrettyCode); "my_lovely_script.js" Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line . There’s a which discusses this. script.async = false; great article on Javascript loading in general Source Code Merge/Preprocessing As mentioned at the top of this answer, many developers use build/transpilation tool(s) like Parcel, Webpack, or Babel in their projects, allowing them to use upcoming JavaScript syntax, provide backward compatibility for older browsers, combine files, minify, perform code-splitting etc. Alternative Answer: If you are looking for something more advanced, try out . You’ll get added benefits such as dependency management, better concurrency, and avoid duplication (that is, retrieving a script more than once). RequireJS You can write your JavaScript files in “modules” and then reference them as dependencies in other scripts. Or you can use RequireJS as a simple “go get this script” solution. Example: Define dependencies as modules: some-dependency.js define([ , ], { libraryObject; }); 'lib/dependency1' 'lib/dependency2' ( ) function d1, d2 //Your actual script goes here. //The dependent scripts will be fetched if necessary. return //For example, jQuery object is your “main” JavaScript file that depends on implementation.js some-dependency.js ([ ], { }); require 'some-dependency' ( ) function dependency //Your script goes here //some-dependency.js is fetched. //Then your script is executed Excerpt from the README:RequireJS loads plain JavaScript files as well as more defined modules. It is optimized for in-browser use, including in a Web Worker, but it can be used in other JavaScript environments, like Rhino and Node. It implements the Asynchronous Module API. GitHub RequireJS uses plain script tags to load modules/files, so it should allow for easy debugging. It can be used simply to load existing JavaScript files, so you can add it to your existing project without having to re-write your JavaScript files. In Conclusion These are the 10 most commonly asked questions about JavaScript. If you have any suggestions or any confusion, please comment below. If you need any help, we will be glad to help you. This post was originally posted on . DevPost by Truemark Previously published at https://thedevpost.com/blog/10-most-asked-questions-about-javascript/