JAVASCRIPT INTERVIEW QUESTIONS - O628

Dineshyadav.com


- Boolean - Null - Undefined - Number - BigInt - String - Symbol - Objects (collection of properties) A falsy value is a value that is considered false when encountered in aBooleancontext. false The keyword false 0 The Number zero -0 The Number negative zero 0n The BigInt zero null null – the absence of any value undefined undefined – the primitive value NaN NaN – not a number Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers).Type conversionis similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit. Example: const value1 = '1';const value2 = 2;let sum = value1 + value2;console.log(sum); - var – Declares a variable, optionally initializing it to a value. - let – Declares a block scope local variable, optionally initializing it to a value. - const – Declares a read-only named constant. - do...while – Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once. - for – Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop. - for...in – Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed. - for...of – Iterates over iterable objects (includingarrays, array-like objects,iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property. - for await...of – Iterates over async iterable objects, array-like objects,iterators and generators, invoking a custom iteration hook with statements to be executed for the value of each distinct property. - while – Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement. Block – A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets. break – Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement. continue – Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration. if...else – Executes a statement if a specified condition is true. If the condition is false, another statement can be executed. switch – Evaluates an expression, matching the expression’s value to a case clause, and executes statements associated with that case. throw – Throws a user-defined exception. try...catch – Marks a block of statements to try, and specifies a response, should an exception be thrown. Q7. What are Functions? JavaScript Interview Questions and Answers to help you find your next JavaScript Developer job. Table of Contents (Close) - Q1. What is JavaScript? - Q2. What are the different data types in JavaScript? - Q3. What are the JavaScript Falsy values? - Q3. Explain Type Coercion in JavaScript. - Q4. Explain Variable Declaration in JavaScript. - Q5. Explain difference Iterations in JavaScript. - Q6. Explain various control flow statements in JavaScript. - Q7. What are Functions? - Q8. What are Events in JavaScript? - Q9. What are different types of errors in JavaScript? - Q10. What is the Document Object Model (DOM)? - Q11. What are Arrays in JavaScript? - Q12. What is Scope in JavaScript? - Q13. What is Hoisting in JavaScript? - Q14. What is Strict Mode in JavaScript? - Q15. What is Closure in JavaScript? - Q16. What are Object Prototypes in JavaScript? - Q17. Explain various Console Methods in JavaScript. - Q18. What are Async Callbacks in JavaScript? - Q19. What are Promises in JavaScript? - Q20. What are Arrow Functions in JavaScript? - Additional Salesforce Interview Questions and Answers Q1. What is JavaScript? JavaScript ( JS ) is a lightweight, interpreted, orjust-in-timecompiled programming language withfirst-class functions. JavaScript is aprototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles. Q2. What are the different data types in JavaScript? The set of types in the JavaScript language consists ofprimitive valuesandobjects. - Primitive values - Boolean - Null - Undefined - Number - BigInt - String - Symbol - Objects (collection of properties) // Booleanlet amIHappy = true;// Numberlet currentYear = 2021;// Stringlet blogName = 'Forcepective.com';// Arraylet carArray = ('Honda', 'Toyota', 'BMW');// Objectlet myCar = {name : 'Honda', make : 'CRV'} Q3. What are the JavaScript Falsy values? A falsy value is a value that is considered false when encountered in aBooleancontext. false The keyword false 0 The Number zero -0 The Number negative zero 0n The BigInt zero “”, ”,“ Empty string value null null – the absence of any value undefined undefined – the primitive value NaN NaN – not a number Q3. Explain Type Coercion in JavaScript. Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers).Type conversionis similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit. Example: const value1 = '1';const value2 = 2;let sum = value1 + value2;console.log(sum); In the above example, JavaScript has coerced the2from a number into a string and then concatenated the two values together, resulting in a string of12. Q4. Explain Variable Declaration in JavaScript. In JavaScript variables can be declared as: - var – Declares a variable, optionally initializing it to a value. - let – Declares a block scope local variable, optionally initializing it to a value. - const – Declares a read-only named constant. Q5. Explain difference Iterations in JavaScript. - do...while – Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once. - for – Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop. - for...in – Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed. - for...of – Iterates over iterable objects (includingarrays, array-like objects,iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property. - for await...of – Iterates over async iterable objects, array-like objects,iterators and generators, invoking a custom iteration hook with statements to be executed for the value of each distinct property. - while – Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement. JavaScript Interview Questions and Answers Q6. Explain various control flow statements in JavaScript. Block – A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets. break – Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement. continue – Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration. Empty – An empty statement is used to provide no statement, although the JavaScript syntax would expect one. if...else – Executes a statement if a specified condition is true. If the condition is false, another statement can be executed. switch – Evaluates an expression, matching the expression’s value to a case clause, and executes statements associated with that case. throw – Throws a user-defined exception. try...catch – Marks a block of statements to try, and specifies a response, should an exception be thrown. Q7. What are Functions? Functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time. In JavaScript functions are essentially special objects. As objects, they are first-class members of JavaScript. They can be assigned as the values of variables, passed into other functions as parameters, and returned from functions. /* Function Declaration */function greeting() { alert('How are you today?');}/* Function Expressions */let myCar = function () { alert('Honda');} Q8. What are Events in JavaScript? Events are code structures that listen for activity in the browser, and run code in response. An example is handling theclick event, which is fired by the browser when you click on something with your mouse. The constructs that listen out for the event happening are called event listeners , and the blocks of code that run in response to the event firing are called event handlers . document.querySelector('ClickMe').onclick = function() { alert('Welcome to Forcepective.com!');} Q9. What are different types of errors in JavaScript? Generally speaking, when you do something wrong in code, there are two main types of error that you’ll come across: - Syntax errors : These are spelling errors in your code that actually cause the program not to run at all, or stop working part way through — you will usually be provided with some error messages too. These are usually okay to fix, as long as you are familiar with the right tools and know what the error messages mean! - Logic errors : These are errors where the syntax is actually correct but the code is not what you intended it to be, meaning that program runs successfully but gives incorrect results. These are often harder to fix than syntax errors, as there usually isn’t an error message to direct you to the source of the error. Q10. What is the Document Object Model (DOM)? The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects; that way, programming languages can interact with the page. A web page is a document that can be either displayed in the browser window or as the HTML source. In both cases, it is the same document but the Document Object Model (DOM) representation allows it to be manipulated. As an object-oriented representation of the web page, it can be modified with a scripting language such as JavaScript. For example, the DOM specifies that the querySelectorAll method in this code snippet must return a list of all the elements in the document: const paragraphs = document.querySelectorAll("p");// paragraphs(0) is the first element// paragraphs(1) is the second element, etc.alert(paragraphs(0).nodeName); JavaScript Interview Questions and Answers Q11. What are Arrays in JavaScript? Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array’s length can change at any time, and data can be stored at non-contiguous locations in the array. Common Array Operations // Create an Arraylet cars = ('Honda', 'Toyota', 'BMW')console.log(cars.length)// 3//Access an Array item using the index positionlet firstCar = cars(0)// Honda//Loop over an Arraycars.forEach(function(item, index, array) { console.log(item, index)})// Honda 0// Totota 1// BMW 2//Remove an item from the beginning of an Arraylet firstCar = cars.shift() // remove Honda from the front// ("Toyota", "BMW")//Add an item to the beginning of an Arraylet newLength = cars.unshift('Ford') // adds Ford to the front// ("Ford", "Toyota", "BMW")//Remove an item from the end of an Arraylet lastCar = cars.pop() // remove BMW from the end// ("Ford", "Toyota")//Add an item to the end of an Arraylet lastCar = cars.push('Audi') // adds Audi to the end// ("Ford", "Toyota", "Audi")// Find the index of an item in the Arraylet toyotaPosition = cars.indexOf('Toyota');// 1// Remove an item by index positionlet removedCar = cars.splice(toyotaPosition, 1);// ("Ford", "Audi")// Copy an Arraylet carsCopy = cars.slice();// ("Ford", "Audi") Q12. What is Scope in JavaScript? Scope is the current context of execution. The context in whichvaluesandexpressionsare “visible” or can be referenced. If avariableor other expression is not “in the current scope,” then it is unavailable for use. Scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa. Variable scope – When you declare a variable outside of any function, it is called aglobalvariable, because it is available to any other code in the current document. When you declare a variable within a function, it is called alocalvariable, because it is available only within that function. In client-side JavaScript, the global scope is generally the web page inside which all the code is being executed. In web pages, the global object is window , so you can set and access global variables using the window.variable syntax. Q13. What is Hoisting in JavaScript? In JavaScript you can refer to a variable declared later, without getting an exception. This concept is known ashoisting.Variables in JavaScript are, in a sense, “hoisted” (or “lifted”) to the top of the function or statement. However, variables that are hoisted return a value of undefined . So even if you declare and initialize after you use or refer to this variable, it still returns undefined . Variables and constants defined with let or cont are not hoisted. console.log(myCar === undefined); // truevar myCar = 'Honda';// The above example will be interpreted as var myCar;console.log(myCar === undefined); // truemyCar = 'Honda'; In the case of functions, only functiondeclarationsare hoisted butnotthe functionexpressions. /* Function declaration */car(); // "Honda"function car() { console.log('Honda');}/* Function expression */ev(); // TypeError: ev is not a functionvar ev = function() { console.log('Tesla');}; Q14. What is Strict Mode in JavaScript? Strict mode, introduced in ECMAScript 5, is a way toopt into a restricted variant of JavaScript. Strict mode applies toentire scriptsor toindividual functions. It doesn’t apply to block statements enclosed in {} braces. Strict mode makes several changes to normal JavaScript semantics: - Eliminates some JavaScript silent errors by changing them to throw errors. - Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode. - Prohibits some syntax likely to be defined in future versions of ECMAScript. // Whole-script strict mode syntax'use strict';var message = "Hi! I'm a strict mode script!";// Strict mode for functionsfunction strict() { // Function-level strict mode syntax 'use strict'; function nested() { return 'And so am I!'; } return "Hi! I'm a strict mode function! " + nested();}function notStrict() { return "I'm not strict."; } The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it. All parts of ECMAScriptclassesare strict mode code, including bothclass declarationsandclass expressions and so also including all parts of class bodies. Q15. What is Closure in JavaScript? When a function is declared, it holds a reference to any variables or arguments declared within it, and any variables it references in the scope that it is contained within. This combination of its variables and arguments along with local variables and arguments from its containing scope is called a closure. Consider thisfunction, and the function it returns. const greetingMaker = function(greeting){ return function(whoGreeting){ return greeting + ", " + whoGreeting + "!"; }}const greetingHello = greetingMaker("Hello");const greetingBonjour = greetingMaker("Bonjour");const greetingCiao = greetingMaker("Ciao");console.log(greetingHello("Gemma")); // Hello, Gemma!console.log(greetingBonjour("Fabien")); // Bonjour, Fabien!console.log(greetingCiao("Emanuela")); // Ciao, Emanuela! When greetingMaker is invoked, we might normally imagine its greeting argument to last only for the life of it being called. But the returned function keeps a reference to the greeting argument in greetingMaker ’s scope. So that finally when it is invoked through greetingHello / Bonjour / Ciao , it’s still accessible. JavaScript Interview Questions and Answers Q16. What are Object Prototypes in JavaScript? Prototypes are the mechanism by which JavaScript objects inherit features from one another. In order to provide inheritance, objects can have a prototype object, which acts as a template object that it inherits methods and properties from. An object’s prototype object may also have a prototype object, which it inherits methods and properties from, and so on. This is often referred to as aprototype chain, and explains why different objects have properties and methods defined on other objects available to them. In JavaScript, a link is made between the object instance and its prototype (its __proto__ property, which is derived from the prototype property on the constructor), and the properties and methods are found by walking up the chain of prototypes. Q17. Explain various Console Methods in JavaScript. The console object provides access to the browser’s debugging console. The console object can be accessed from any global object. Some of the key console methods are: /* Outputting text to the console */console.log("Some Message");console.info("Some Message");console.warn("Some Message");console.error("Some Message");/* Using groups in console */console.group("First group");console.log("In the first group");console.groupEnd();/* Timers */console.time("answer time");alert("Click to continue");console.timeLog("answer time");alert("Do a bunch of other stuff...");console.timeEnd("answer time");/* Stack Trace */console.trace(); Q18. What are Async Callbacks in JavaScript? Async callbacks are functions that are specified as arguments when calling a function which will start executing code in the background. When the background code finishes running, it calls the callback function to let you know the work is done. /* An example of an async callback is the second parameter of the addEventListener() method. The first parameter is the type of event to be listened for, and the second parameter is a callback function that is invoked when the event is fired */btn.addEventListener('clickMe', () => { alert('You clicked me!'); let pElem = document.createElement('p'); pElem.textContent = 'This is a newly-added paragraph.'; document.body.appendChild(pElem);}); When we pass a callback function as an argument to another function, we are only passing the function’s reference as an argument, i.e, the callback function isnotexecuted immediately. It is “called back” (hence the name) asynchronously somewhere inside the containing function’s body. The containing function is responsible for executing the callback function when the time comes. Q19. What are Promises in JavaScript? Promises are the new style of async code. A Promise is an object that represents an intermediate state of an operation — in effect, apromisethat a result of some kind will be returned at some point in the future. There is no guarantee of exactly when the operation will complete and the result will be returned, but there is a guarantee that when the result is available, or the promise fails, the code you provide will be executed in order to do something else with a successful result, or to gracefully handle a failure case. A promise has following states: - Pending – When a promise is created, it is neither in a success or failure state.It’s said to be pending - Resolved – When a promise returns, it is said to beresolved - Fulfilled – A successfully resolved promise is said to befulfilled. It returns a value, which can be accessed by chaining a .then() block onto the end of the promise chain. The callback function inside the .then() block will contain the promise’s return value - Rejected – An unsuccessful resolved promise is said to berejected. It returns areason, an error message stating why the promise was rejected. This reason can be accessed by chaining a .catch() block onto the end of the promise chain. /* Create new Promise using Constructor */function welcomePromise(message, interval) { return new Promise((resolve, reject) => { if (message === '' || typeof message !== 'string') { reject('Message is empty or not a string'); } else if (interval <0 || typeof interval !== 'number') { reject('Interval is negative or not a number'); } else { setTimeout(() => { resolve(message); }, interval); } });}/* Invoking welcomePromise function */welcomePromise('Welcome to Forcepective.com', 1000).then(message => { alert(message);}).catch(e => { console.log('Error: ' + e);}); Q20. What are Arrow Functions in JavaScript? Anarrow function expressionis a compactalternative to a traditionalfunction expression. Arrow function key differences vs traditional functions: - Does not have its own bindings to this or super , and should not be used as methods . - Does not have new.target keyword. - Not suitable for call , apply and bind methods, which generally rely on establishing ascope. - Can notbe used asconstructors. - Can not use yield , within its body. /* Arrow Function Syntax *//* One param */param => expression /* Multiple param */(param1, paramN) => expression/* Multiple params require parentheses. Multiline statements require body braces and return */(param1, paramN) => { let a = 1; return a + param1 + paramN;}/* Rest Paramaters */(a, b, ...r) => expression/* Default parameters */(a=10, b=20, c) => expression This article will be updated soon, please come back for more real word, frequently asked JavaScript Interview Questions & Answers! Additional Salesforce Interview Questions and Answers - Salesforce Integration Interview Questions - Salesforce CPQ Interview Questions - Salesforce Developer Interview Questions - Salesforce Field Service Interview Questions - Vlocity (Salesforce Industries) Interview Questions #J-18808-Ljbffr

trabajosonline.net © 2017–2021
Más información