├── .gitignore ├── code ├── 001 │ └── script.js ├── 005 │ └── script.js ├── 009 │ └── script.js ├── 008 │ └── script.js ├── 041 │ └── script.js ├── 002 │ └── script.js ├── 004 │ └── script.js ├── 021 │ └── script.js ├── 019 │ └── script.js ├── 020 │ └── script.js ├── 027 │ └── script.js ├── 028 │ └── script.js ├── 029 │ └── script.js ├── 006 │ └── script.js ├── 023 │ └── script.js ├── 026 │ └── script.js ├── 030 │ └── script.js ├── 022 │ └── script.js ├── 013 │ └── script.js ├── 007 │ └── script.js ├── 031 │ └── script.js ├── 040 │ ├── script.mjs │ └── module.mjs ├── 039 │ └── script.js ├── 012 │ └── script.js ├── 015 │ └── script.js ├── 003 │ └── script.js ├── 032 │ └── script.js ├── 011 │ └── script.js ├── 024 │ └── script.js ├── 033 │ └── script.js ├── 036 │ └── script.js ├── 018 │ └── script.js ├── 037 │ └── script.js ├── 035 │ └── script.js ├── miscellaneous │ └── 001 │ │ └── script.js ├── 034 │ └── script.js ├── 025 │ └── script.js ├── 014 │ └── script.js ├── 017 │ └── script.js ├── 010 │ └── script.js └── 038 │ └── script.js ├── .husky └── pre-commit ├── .prettierrc ├── package.json ├── LICENSE ├── CODE_OF_CONDUCT.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea 3 | node_modules -------------------------------------------------------------------------------- /code/001/script.js: -------------------------------------------------------------------------------- 1 | console.log(new Date(2023, 0, 31).toDateString()) 2 | -------------------------------------------------------------------------------- /code/005/script.js: -------------------------------------------------------------------------------- 1 | console.log(undefined == null, undefined === null) 2 | -------------------------------------------------------------------------------- /code/009/script.js: -------------------------------------------------------------------------------- 1 | console.log(isFinite(Infinity), isNaN(Infinity)) 2 | -------------------------------------------------------------------------------- /code/008/script.js: -------------------------------------------------------------------------------- 1 | console.log('BG Web Agency' === NaN, isNaN('BG Web Agency')) 2 | -------------------------------------------------------------------------------- /code/041/script.js: -------------------------------------------------------------------------------- 1 | // foo.js 2 | function foo() { 3 | console.log(`Foo`) 4 | } 5 | export { foo } 6 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | npx pretty-quick --staged 5 | -------------------------------------------------------------------------------- /code/002/script.js: -------------------------------------------------------------------------------- 1 | var username = 'kirandash' 2 | var username = 'bgwebagency' 3 | 4 | console.log(username) 5 | -------------------------------------------------------------------------------- /code/004/script.js: -------------------------------------------------------------------------------- 1 | const len1 = 'kiran'.length 2 | const len2 = '👻'.length 3 | 4 | console.log(len1, len2) 5 | -------------------------------------------------------------------------------- /code/021/script.js: -------------------------------------------------------------------------------- 1 | const myArray = [1, 2, 3, 4, 5] 2 | const poppedValue = myArray.pop() 3 | console.log(poppedValue) 4 | -------------------------------------------------------------------------------- /code/019/script.js: -------------------------------------------------------------------------------- 1 | let arr = [1, 2, 3, 4] 2 | let result = arr.push(5) 3 | console.log('result: ', result, 'arr: ', arr) 4 | -------------------------------------------------------------------------------- /code/020/script.js: -------------------------------------------------------------------------------- 1 | let arr = [3, 5, 7, 9] 2 | let result = arr.unshift(1, 2) 3 | console.log('result: ', result, 'arr: ', arr) 4 | -------------------------------------------------------------------------------- /code/027/script.js: -------------------------------------------------------------------------------- 1 | const numbers = [1, 2, 3, 4, 5] 2 | const sum = numbers.reduce((acc, val) => acc + val) 3 | console.log(sum) 4 | -------------------------------------------------------------------------------- /code/028/script.js: -------------------------------------------------------------------------------- 1 | const arr = [1, 2, 3, 4] 2 | const result = arr.reduceRight((acc, curr) => acc + curr) 3 | console.log(result) 4 | -------------------------------------------------------------------------------- /code/029/script.js: -------------------------------------------------------------------------------- 1 | const arr = ['Centauri', undefined, 3.14159, 'canine', 11235] 2 | const result = arr.sort() 3 | console.log(result) 4 | -------------------------------------------------------------------------------- /code/006/script.js: -------------------------------------------------------------------------------- 1 | function getFruits(x, y, ...multi) { 2 | console.log(x, y, multi) 3 | } 4 | getFruits('🍎', '🍌', '🍇', '🍊', '🍍') 5 | -------------------------------------------------------------------------------- /code/023/script.js: -------------------------------------------------------------------------------- 1 | let arr = [1, 2, 3, 4, 5] 2 | let removed = arr.splice(1, 2, 'a', 'b') 3 | onsole.log('removed:', removed, 'arr: ', arr) 4 | -------------------------------------------------------------------------------- /code/026/script.js: -------------------------------------------------------------------------------- 1 | const numbers = [1, 2, 3, 4, 5] 2 | const doubledNumbers = numbers.map(num => num * 2) 3 | console.log(doubledNumbers) 4 | -------------------------------------------------------------------------------- /code/030/script.js: -------------------------------------------------------------------------------- 1 | let numbers = [1, 2, 3, undefined, 6, 7, 8, 9] 2 | 3 | let [a, , b, c = 2, ...rest] = numbers 4 | 5 | console.log(a, b, c, rest) 6 | -------------------------------------------------------------------------------- /code/022/script.js: -------------------------------------------------------------------------------- 1 | const arr = [10, 20, 30, 40, 50] 2 | const removedElement = arr.shift() 3 | console.log('removedElement: ', removedElement, 'arr: ', arr) 4 | -------------------------------------------------------------------------------- /code/013/script.js: -------------------------------------------------------------------------------- 1 | function multiply(x) { 2 | return function (y) { 3 | return x * y 4 | } 5 | } 6 | 7 | const double = multiply(2) 8 | 9 | console.log(double(5)) 10 | -------------------------------------------------------------------------------- /code/007/script.js: -------------------------------------------------------------------------------- 1 | let x = Number.NEGATIVE_INFINITY // Infinity 2 | let y = Number.POSITIVE_INFINITY // -Infinity 3 | let z = x + y // NaN 4 | console.info(x, y) 5 | console.log(z) 6 | -------------------------------------------------------------------------------- /code/031/script.js: -------------------------------------------------------------------------------- 1 | const date1 = new Date() 2 | const date2 = new Date('1995-12-17T05:10:00') 3 | const date3 = new Date('1995-10-15T08:12:15+02:00') 4 | 5 | console.log(date1, '', date2, '', date3) 6 | -------------------------------------------------------------------------------- /code/040/script.mjs: -------------------------------------------------------------------------------- 1 | import calculateCircumference, { PI, calculateArea } from './module.mjs'; 2 | 3 | console.log(PI); 4 | console.log(calculateArea(5)); 5 | console.log(calculateCircumference(5)); 6 | -------------------------------------------------------------------------------- /code/039/script.js: -------------------------------------------------------------------------------- 1 | const person = { 2 | name: 'John', 3 | age: 30, 4 | city: 'New York', 5 | } 6 | 7 | const { name, age, city } = person 8 | 9 | console.log(name) 10 | console.log(age) 11 | console.log(city) 12 | -------------------------------------------------------------------------------- /code/012/script.js: -------------------------------------------------------------------------------- 1 | function add(x) { 2 | return function (y) { 3 | if (y !== undefined) { 4 | x += y 5 | return arguments.callee 6 | } else { 7 | return x 8 | } 9 | } 10 | } 11 | 12 | console.log(add(1)(2)(3)()) 13 | -------------------------------------------------------------------------------- /code/040/module.mjs: -------------------------------------------------------------------------------- 1 | export const PI = 3.14159; 2 | 3 | export function calculateArea(radius) { 4 | return PI * radius * radius; 5 | } 6 | 7 | export default function calculateCircumference(radius) { 8 | return 2 * PI * radius; 9 | } -------------------------------------------------------------------------------- /code/015/script.js: -------------------------------------------------------------------------------- 1 | function* counter() { 2 | let i = 0 3 | while (true) { 4 | yield i++ 5 | } 6 | } 7 | 8 | const gen = counter() 9 | 10 | console.log(gen.next().value) 11 | console.log(gen.next().value) 12 | console.log(gen.next().value) 13 | -------------------------------------------------------------------------------- /code/003/script.js: -------------------------------------------------------------------------------- 1 | // update username for user with arrow function 2 | const user = { 3 | username: 'kirandash', 4 | updateUsername: newName => { 5 | this.username = newName 6 | }, 7 | } 8 | 9 | user.updateUsername('bgwebagency') 10 | console.log(user.username) 11 | -------------------------------------------------------------------------------- /code/032/script.js: -------------------------------------------------------------------------------- 1 | const date = new Date('Mart 15, 1975 23:15:30') 2 | date.setMinutes(10) 3 | date.setUTCDate(5) 4 | 5 | console.log( 6 | 'Minutes:' + date.getMinutes() + ',', 7 | '', 8 | 'Year:' + date.getFullYear() + ',', 9 | '', 10 | 'UTCDate:' + date.getUTCDate(), 11 | ) 12 | -------------------------------------------------------------------------------- /code/011/script.js: -------------------------------------------------------------------------------- 1 | // PROBLEM 2 | for (var i = 0; i < 3; i++) { 3 | setTimeout(function () { 4 | console.log(i) 5 | }, 0) 6 | } 7 | 8 | // SOLUTION 9 | for (var i = 0; i < 3; i++) { 10 | ;(function (j) { 11 | setTimeout(function () { 12 | console.log(j) 13 | }, 0) 14 | })(i) 15 | } 16 | -------------------------------------------------------------------------------- /code/024/script.js: -------------------------------------------------------------------------------- 1 | const fruits = ['apple', 'banana', 'orange', 'grape', 'apple', 'kiwi'] 2 | const index = fruits.indexOf('orange') 3 | const lastIndex = fruits.lastIndexOf('apple') 4 | const result = fruits.includes('grape') 5 | console.log('index: ', index, 'lastIndex: ', lastIndex, 'result: ', result) 6 | -------------------------------------------------------------------------------- /code/033/script.js: -------------------------------------------------------------------------------- 1 | const date1 = new Date('2023-5-1') 2 | const next_us_election = new Date('2024-11-5') 3 | const difference_in_time = next_us_election.getTime() - date1.getTime() 4 | const difference_in_days = difference_in_time / (1000 * 3600 * 24) 5 | console.log(parseInt(difference_in_days, 10) + ' Days') 6 | -------------------------------------------------------------------------------- /code/036/script.js: -------------------------------------------------------------------------------- 1 | function greet(name) { 2 | console.log(`Hello, ${name}! Welcome to ${this.location}.`) 3 | } 4 | 5 | const person = { 6 | location: 'New York', 7 | } 8 | 9 | greet.call(person, 'John') 10 | greet.apply(person, ['Alex']) 11 | const greetPerson = greet.bind(person) 12 | greetPerson('Thomas') 13 | -------------------------------------------------------------------------------- /code/018/script.js: -------------------------------------------------------------------------------- 1 | const arr = [1, 2, 3, 4, 5] 2 | let sum = 0 3 | for (let num of arr) { 4 | sum += num 5 | if (sum >= 6) break 6 | } 7 | console.log(sum) 8 | 9 | const arr2 = [1, 2, 3, 4, 5] 10 | let sum2 = 0 11 | arr.forEach(num => { 12 | sum2 += num 13 | // if(sum2 >= 6) break; 14 | }) 15 | console.log(sum2) 16 | -------------------------------------------------------------------------------- /code/037/script.js: -------------------------------------------------------------------------------- 1 | class Animal { 2 | constructor(name) { 3 | this.name = name 4 | } 5 | static makeSound() { 6 | console.log('Generic animal sound') 7 | } 8 | sayName() { 9 | console.log(`My name is ${this.name}`) 10 | } 11 | } 12 | 13 | const a1 = new Animal('Lion') 14 | const a2 = new Animal('Time') 15 | 16 | Animal.makeSound() 17 | a1.makeSound() 18 | a2.makeSound() 19 | -------------------------------------------------------------------------------- /code/035/script.js: -------------------------------------------------------------------------------- 1 | function User(username) { 2 | this.username = username 3 | 4 | this.updateUsername = newName => { 5 | this.username = newName 6 | } 7 | } 8 | 9 | const user1 = new User('kirandash') 10 | const user2 = new User('bgwebagency') 11 | 12 | user1.updateUsername('kirandash-website') 13 | user2.updateUsername('bgwebagency-app') 14 | 15 | console.log(user1.username, user2.username) 16 | -------------------------------------------------------------------------------- /code/miscellaneous/001/script.js: -------------------------------------------------------------------------------- 1 | function replacer(key, value) { 2 | if (typeof value === 'Date') { 3 | return value.toJSON() 4 | } else if (typeof value === 'RegExp') { 5 | return value.toString() 6 | } else { 7 | return value 8 | } 9 | } 10 | 11 | const object = { 12 | date: new Date(), 13 | regex: /some regex/, 14 | } 15 | 16 | const jsonString = JSON.stringify(object, replacer) 17 | console.log(jsonString) 18 | -------------------------------------------------------------------------------- /code/034/script.js: -------------------------------------------------------------------------------- 1 | let person = { 2 | name: 'John', 3 | age: 30, 4 | hobbies: ['reading', 'traveling', 'cooking'], 5 | address: { 6 | street: '123 Main St', 7 | city: 'New York', 8 | state: 'NY', 9 | }, 10 | sayHello: function () { 11 | console.log('Hello, my name is ' + this.name) 12 | }, 13 | } 14 | 15 | console.log(person.name) 16 | console.log(person.hobbies[1]) 17 | console.log(person.address.city) 18 | 19 | person.sayHello() 20 | -------------------------------------------------------------------------------- /code/025/script.js: -------------------------------------------------------------------------------- 1 | function isDivisibleBy7(num) { 2 | return num % 7 == 0 3 | } 4 | 5 | const nums = [28, 7, 3, 29, 15, 1, 2, 23] 6 | const filterResult = nums.filter(isDivisibleBy7) 7 | const findResult = nums.find(num => num < 10) 8 | const findIndexResult = nums.findIndex(num => num / 2 == 14) 9 | 10 | console.log( 11 | 'filterResult:', 12 | filterResult, 13 | 'findResult:', 14 | findResult, 15 | 'findIndexResult:', 16 | findIndexResult, 17 | ) 18 | -------------------------------------------------------------------------------- /code/014/script.js: -------------------------------------------------------------------------------- 1 | // Define an object with a custom iterator 2 | const myIterable = { 3 | values: [1, 2, 3, 4, 5], 4 | [Symbol.iterator]() { 5 | let i = 0 6 | return { 7 | next: () => { 8 | if (i >= this.values.length) { 9 | return { value: undefined, done: true } 10 | } else { 11 | return { value: this.values[i++], done: false } 12 | } 13 | }, 14 | } 15 | }, 16 | } 17 | 18 | // Use a for...of loop to iterate over the iterable 19 | for (const value of myIterable) { 20 | console.log(value) 21 | } 22 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "avoid", 3 | "bracketSameLine": false, 4 | "bracketSpacing": true, 5 | "embeddedLanguageFormatting": "auto", 6 | "endOfLine": "lf", 7 | "htmlWhitespaceSensitivity": "css", 8 | "insertPragma": false, 9 | "jsxSingleQuote": false, 10 | "printWidth": 80, 11 | "proseWrap": "always", 12 | "quoteProps": "as-needed", 13 | "requirePragma": false, 14 | "semi": false, 15 | "singleAttributePerLine": false, 16 | "singleQuote": true, 17 | "tabWidth": 2, 18 | "trailingComma": "all", 19 | "useTabs": true 20 | } 21 | -------------------------------------------------------------------------------- /code/017/script.js: -------------------------------------------------------------------------------- 1 | function getData() { 2 | return new Promise((resolve, reject) => { 3 | setTimeout(() => { 4 | resolve('Data retrieved successfully') 5 | }, 1000) 6 | }) 7 | } 8 | 9 | async function main() { 10 | try { 11 | const data = await getData() 12 | console.log(data) 13 | throw new Error('Something went wrong') 14 | } catch (err) { 15 | console.log('Caught an error:', err.message) 16 | return 'Error occurred' 17 | } finally { 18 | console.log('Finally block executed.') 19 | return 'Finally block value' 20 | } 21 | } 22 | 23 | console.log(main()) 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "who-wants-to-be-a-javascriptaire", 3 | "version": "1.0.0", 4 | "description": "JavaScript multiple choice questions with answers and video explanation to help you with Frontend/Web coding interviews", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "prettier": "prettier --write \"**/*.js\"", 9 | "check-format": "prettier --list-different \"**/*.js\"", 10 | "format": "npm run prettier" 11 | }, 12 | "keywords": [], 13 | "author": "", 14 | "license": "ISC", 15 | "devDependencies": { 16 | "husky": "^8.0.3", 17 | "prettier": "^2.8.8", 18 | "pretty-quick": "3.1.3" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /code/010/script.js: -------------------------------------------------------------------------------- 1 | console.log('==== PROBLEM ====') 2 | const user = { 3 | name: 'John', 4 | age: 30, 5 | getName: () => { 6 | return this.name 7 | }, 8 | getAge: function () { 9 | return this.age 10 | }, 11 | } 12 | 13 | const getName = user.getName 14 | const getAge = user.getAge 15 | 16 | console.log(getName()) 17 | console.log(getAge()) 18 | 19 | console.log('==== SOLUTION ====') 20 | const user2 = { 21 | name: 'John', 22 | age: 30, 23 | getName: function () { 24 | // change arrow function to regular function 25 | return this.name 26 | }, 27 | getAge: function () { 28 | return this.age 29 | }, 30 | } 31 | 32 | // do not assign the function to a variable 33 | console.log(user2.getName()) 34 | console.log(user2.getAge()) 35 | -------------------------------------------------------------------------------- /code/038/script.js: -------------------------------------------------------------------------------- 1 | function Animal(name) { 2 | this.name = name 3 | } 4 | 5 | Animal.prototype.eat = function () { 6 | console.log(this.name + ' is eating.') 7 | } 8 | 9 | function Dog(name) { 10 | Animal.call(this, name) 11 | } 12 | 13 | Dog.prototype = Object.create(Animal.prototype) 14 | Dog.prototype.constructor = Dog 15 | 16 | Dog.prototype.bark = function () { 17 | console.log(this.name + ' is barking.') 18 | } 19 | 20 | function CustomArray() { 21 | Array.call(this) 22 | } 23 | 24 | CustomArray.prototype = Object.create(Array.prototype) 25 | CustomArray.prototype.constructor = CustomArray 26 | 27 | CustomArray.prototype.sum = function () { 28 | return this.reduce((acc, val) => acc + val, 0) 29 | } 30 | 31 | var dog = new Dog('Buddy') 32 | dog.eat() 33 | dog.bark() 34 | 35 | var numbers = new CustomArray() 36 | numbers.push(1, 2, 3, 4, 5) 37 | console.log(numbers.sum()) 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2023 BG Web Agency 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | # Contributor Covenant Code of Conduct 3 | 4 | ## Our Pledge 5 | 6 | We as members, contributors, and leaders pledge to make participation in our 7 | community a harassment-free experience for everyone, regardless of age, body 8 | size, visible or invisible disability, ethnicity, sex characteristics, gender 9 | identity and expression, level of experience, education, socio-economic status, 10 | nationality, personal appearance, race, caste, color, religion, or sexual 11 | identity and orientation. 12 | 13 | We pledge to act and interact in ways that contribute to an open, welcoming, 14 | diverse, inclusive, and healthy community. 15 | 16 | ## Our Standards 17 | 18 | Examples of behavior that contributes to a positive environment for our 19 | community include: 20 | 21 | * Demonstrating empathy and kindness toward other people 22 | * Being respectful of differing opinions, viewpoints, and experiences 23 | * Giving and gracefully accepting constructive feedback 24 | * Accepting responsibility and apologizing to those affected by our mistakes, 25 | and learning from the experience 26 | * Focusing on what is best not just for us as individuals, but for the overall 27 | community 28 | 29 | Examples of unacceptable behavior include: 30 | 31 | * The use of sexualized language or imagery, and sexual attention or advances of 32 | any kind 33 | * Trolling, insulting or derogatory comments, and personal or political attacks 34 | * Public or private harassment 35 | * Publishing others' private information, such as a physical or email address, 36 | without their explicit permission 37 | * Other conduct which could reasonably be considered inappropriate in a 38 | professional setting 39 | 40 | ## Enforcement Responsibilities 41 | 42 | Community leaders are responsible for clarifying and enforcing our standards of 43 | acceptable behavior and will take appropriate and fair corrective action in 44 | response to any behavior that they deem inappropriate, threatening, offensive, 45 | or harmful. 46 | 47 | Community leaders have the right and responsibility to remove, edit, or reject 48 | comments, commits, code, wiki edits, issues, and other contributions that are 49 | not aligned to this Code of Conduct, and will communicate reasons for moderation 50 | decisions when appropriate. 51 | 52 | ## Scope 53 | 54 | This Code of Conduct applies within all community spaces, and also applies when 55 | an individual is officially representing the community in public spaces. 56 | Examples of representing our community include using an official e-mail address, 57 | posting via an official social media account, or acting as an appointed 58 | representative at an online or offline event. 59 | 60 | ## Enforcement 61 | 62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 63 | reported to the community leaders responsible for enforcement at 64 | [kirankdash](https://twitter.com/kirankdash). 65 | All complaints will be reviewed and investigated promptly and fairly. 66 | 67 | All community leaders are obligated to respect the privacy and security of the 68 | reporter of any incident. 69 | 70 | ## Enforcement Guidelines 71 | 72 | Community leaders will follow these Community Impact Guidelines in determining 73 | the consequences for any action they deem in violation of this Code of Conduct: 74 | 75 | ### 1. Correction 76 | 77 | **Community Impact**: Use of inappropriate language or other behavior deemed 78 | unprofessional or unwelcome in the community. 79 | 80 | **Consequence**: A private, written warning from community leaders, providing 81 | clarity around the nature of the violation and an explanation of why the 82 | behavior was inappropriate. A public apology may be requested. 83 | 84 | ### 2. Warning 85 | 86 | **Community Impact**: A violation through a single incident or series of 87 | actions. 88 | 89 | **Consequence**: A warning with consequences for continued behavior. No 90 | interaction with the people involved, including unsolicited interaction with 91 | those enforcing the Code of Conduct, for a specified period of time. This 92 | includes avoiding interactions in community spaces as well as external channels 93 | like social media. Violating these terms may lead to a temporary or permanent 94 | ban. 95 | 96 | ### 3. Temporary Ban 97 | 98 | **Community Impact**: A serious violation of community standards, including 99 | sustained inappropriate behavior. 100 | 101 | **Consequence**: A temporary ban from any sort of interaction or public 102 | communication with the community for a specified period of time. No public or 103 | private interaction with the people involved, including unsolicited interaction 104 | with those enforcing the Code of Conduct, is allowed during this period. 105 | Violating these terms may lead to a permanent ban. 106 | 107 | ### 4. Permanent Ban 108 | 109 | **Community Impact**: Demonstrating a pattern of violation of community 110 | standards, including sustained inappropriate behavior, harassment of an 111 | individual, or aggression toward or disparagement of classes of individuals. 112 | 113 | **Consequence**: A permanent ban from any sort of public interaction within the 114 | community. 115 | 116 | ## Attribution 117 | 118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 119 | version 2.1, available at 120 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. 121 | 122 | Community Impact Guidelines were inspired by 123 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. 124 | 125 | For answers to common questions about this code of conduct, see the FAQ at 126 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at 127 | [https://www.contributor-covenant.org/translations][translations]. 128 | 129 | [homepage]: https://www.contributor-covenant.org 130 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html 131 | [Mozilla CoC]: https://github.com/mozilla/diversity 132 | [FAQ]: https://www.contributor-covenant.org/faq 133 | [translations]: https://www.contributor-covenant.org/translations 134 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |

Who Wants to be a JavaScriptaire?

4 | 5 | Fun way to learn JavaScript for your Frontend/Web coding interviews. All the 6 | questions are answered here in text and also have a video on our YouTube 7 | channel. Click the ▶️ icon next to the questions if you prefer to watch the 8 | video explanation. 9 | 10 | Feel free to reach us on our social platforms! 😊
11 | Discord || 12 | Instagram || 13 | Twitter || 14 | TikTok || 15 | Blog || 16 | Facebook 17 | 18 | 🙏 Support 19 | 20 | Please ⭐️ star this project and share it with others to show your support. 21 | [Follow me](https://github.com/kirandash) ❤️ for updates on future projects and 22 | tutorials! 23 | 24 | --- 25 | 26 |
27 | 28 | ## Table of Contents 29 | 30 | [Language Basics](#1-what-will-this-code-output-%EF%B8%8F) - 31 | [Arrays](#18-array-and-traversal-in-array-%EF%B8%8F) - 32 | [Date and Time](#31-date-in-javascript) - 33 | [Object Oriented JavaScript](#34-object-literals-in-javascript) - 34 | [Modules](#40-javascript-modules-import-and-export-in-es6) - 35 | [Miscellaneous](#misc-1-javascript-json-level-medium) 36 | 37 | --- 38 | 39 | ###### 1. What will this code output? [▶️](https://www.youtube.com/shorts/Uysa8_Aa5Sg) 40 | 41 | ```javascript 42 | console.log(new Date(2023, 1, 31)) 43 | ``` 44 | 45 | - A: `Tue Jan 31 2024` 46 | - B: `Tue Jan 31 2023` 47 | - C: `Fri Mar 03 2023` 48 | - D: `Error` 49 | 50 |
Answer 51 |

52 | 53 | #### Answer: C 54 | 55 | In JavaScript, while constructing dates using Date objects months are 0 based. 56 | Which means 0 is for January and 1 is for February. 57 | 58 | So, in this case we are asking JavaScript to set a date of 2023 February 31st 59 | which does not exist. 60 | 61 | But instead of throwing error JavaScript will overflow it to the next month 62 | which is March. 63 | 64 | And since February in 2023 has only 28 days, the code will overflow by 3 days 65 | making the result to be 3rd March 2023. 66 | 67 |

68 |
69 | 70 | --- 71 | 72 | ###### 2. What will this code output? [▶️](https://www.youtube.com/shorts/s6khiRq6EoE) 73 | 74 | ```javascript 75 | var username = 'kirandash' 76 | var username = 'bgwebagency' 77 | 78 | console.log(username) 79 | ``` 80 | 81 | - A: `bgwebagency` 82 | - B: `kirandash` 83 | - C: `ReferenceError` 84 | - D: `SyntaxError` 85 | 86 |
Answer 87 |

88 | 89 | #### Answer: A 90 | 91 | We can declare the same variable multiple times using the `var` keyword. And the 92 | variable will hold the value which it was assigned in the end. 93 | 94 | But we can not declare the same variable multiple times using `let` or `const` 95 | 96 |

97 |
98 | 99 | --- 100 | 101 | ###### 3. What will this code output? [▶️](https://www.youtube.com/shorts/l07LPzBQqTM) 102 | 103 | ```javascript 104 | const user = { 105 | username: 'kirandash', 106 | updateUsername: newName => { 107 | this.username = newName 108 | }, 109 | } 110 | 111 | user.updateUsername('bgwebagency') 112 | console.log(user.username) 113 | ``` 114 | 115 | - A: `bgwebagency` 116 | - B: `ReferenceError` 117 | - C: `kirandash` 118 | - D: `undefined` 119 | 120 |
Answer 121 |

122 | 123 | #### Answer: C 124 | 125 | Because the `updateUsername` function is not working properly and is failing to 126 | update the `username` of the `user`. 127 | 128 | The `updateUsername` function in user `object` is an arrow function, and is not 129 | bound to the `user` object. 130 | 131 | So, the `this` keyword inside updateUsername function is not referring to the 132 | `user` object, but refers to the global scope. 133 | 134 | To fix this issue, we should change the arrow function to a normal function. 135 | 136 |

137 |
138 | 139 | --- 140 | 141 | ###### 4. What will this code output? [▶️](https://www.youtube.com/shorts/CL53e5FucAM) 142 | 143 | ```javascript 144 | const len1 = 'kiran'.length 145 | const len2 = '👻'.length 146 | 147 | console.log(len1, len2) 148 | ``` 149 | 150 | - A: `5, 2` 151 | - B: `5, 1` 152 | - C: `5, undefined` 153 | - D: `5, SyntaxError` 154 | 155 |
Answer 156 |

157 | 158 | #### Answer: A 159 | 160 | In JavaScript, the string length property returns the number of bytes and not 161 | the number of characters like we expect. 162 | 163 | An emoji is a unicode character which is encoded in two bytes. Therefore the 164 | answer is 2 for this question. 165 | 166 | The string length for `kiran` returns `5` because in a string each character is 167 | 1 byte. 168 | 169 |

170 |
171 | 172 | --- 173 | 174 | ###### 5. Difference between undefined and null [▶️](https://www.youtube.com/shorts/tQwec4ELIg8) 175 | 176 | ```javascript 177 | console.log(undefined == null, undefined === null) 178 | ``` 179 | 180 | - A: `true, true` 181 | - B: `true, false` 182 | - C: `false, false` 183 | - D: `false, true` 184 | 185 |
Answer 186 |

187 | 188 | #### Answer: B 189 | 190 | First let me explain the difference between equal and strict equal operator. 191 | 192 | The equal operator only checks if both the values are equal. The strict equal 193 | operator checks if both value and type are equal. 194 | 195 | So in this code, the first statement `undefined == null` returns `true` since 196 | both `undefined` and `null` have the same value which is empty. 197 | 198 | But the second statement `undefined === null` returns `false`. Since 199 | `typeof undefined` is `undefined`, whereas `typeof null` is an `object`. 200 | 201 | You might be wondering, why `typeof null` is an `object` when `null` is 202 | basically a primitive data type. This basically is a mistake in JavaScript since 203 | the beginning. 204 | 205 | Now, one more tip for you: when you want to set an empty value for a variable 206 | use `null` instead of `undefined`. Since `undefined` is mainly used to check if 207 | a variable has no value assigned to it. 208 | 209 |

210 |
211 | 212 | --- 213 | 214 | ###### 6. Rest Operator [▶️](https://www.youtube.com/shorts/7jLCMwhe2VA) 215 | 216 | ```javascript 217 | function getFruits(x, ...multi, y) { 218 | console.log(x, y, multi); 219 | } 220 | getFruits("🍎", "🍌", "🍇", "🍊", "🍍") 221 | ``` 222 | 223 | - A: `🍎 🍍 ["🍌", "🍇", "🍊"]` 224 | - B: `SyntaxError` 225 | 226 |
Answer 227 |

228 | 229 | #### Answer: B 230 | 231 | Rest operators were added as a part of ES6 feature. 232 | 233 | It takes all the arguments passed to a function and puts it in an array. 234 | 235 | If multiple arguments are passed to a function then rest operator must come at 236 | the end. That's why this code snippet will throw an error. 237 | 238 | To fix this issue, please move the rest operator to the end and then it should 239 | work. 240 | 241 |

242 |
243 | 244 | --- 245 | 246 | ###### 7. Infinity and -Infinity [▶️](https://youtube.com/shorts/J3-ab21VMKA) 247 | 248 | ```javascript 249 | let x = Number.NEGATIVE_INFINITY 250 | let y = Number.POSITIVE_INFINITY 251 | let z = x + y 252 | console.log(z) 253 | ``` 254 | 255 | - A: `0` 256 | - B: `undefined` 257 | - C: `NaN` 258 | - D: `TypeError` 259 | 260 |
Answer 261 |

262 | 263 | #### Answer: C 264 | 265 | NEGATIVE_INFINITY and POSITIVE_INFINITY are properties of the Number object in 266 | JavaScript that represents the mathematical concept of negative infinity and 267 | positive infinity. 268 | 269 | When you add Number.NEGATIVE_INFINITY and Number.POSITIVE_INFINITY, the result 270 | is NaN. 271 | 272 | Adding a positive infinite value to a negative infinite value does not result in 273 | a meaningful numerical value. 274 | 275 | So in this case, z will be NaN. 276 | 277 | Note that the code will not throw a TypeError, as JavaScript is able to perform 278 | the addition operation between Number.NEGATIVE_INFINITY and 279 | Number.POSITIVE_INFINITY. 280 | 281 |

282 |
283 | 284 | --- 285 | 286 | ###### 8. isNaN() function [▶️](https://youtube.com/shorts/IyQ5Gr1jtQI) 287 | 288 | ```javascript 289 | console.log('BG Web Agency' === NaN, isNaN('BG Web Agency')) 290 | ``` 291 | 292 | - A: `true, true` 293 | - B: `false, true` 294 | - C: `true, false` 295 | - D: `false, false` 296 | 297 |
Answer 298 |

299 | 300 | #### Answer: B 301 | 302 | Using ` === NaN` to check if a value is a number will not work. 303 | 304 | In JavaScript, `NaN` (Not a Number) is a special value that represents an 305 | invalid number. 306 | 307 | NaN is not equal to anything, including itself, so the expression 308 | `"BG Web Agency" === NaN` will always return `false`. 309 | 310 | To check if a value is a number in JavaScript, you can use the `isNaN()` 311 | function. This function returns `true` if the argument passed to it is `NaN`, or 312 | if it cannot be converted to a number. 313 | 314 |

315 |
316 | 317 | --- 318 | 319 | ###### 9. isFinite() function [▶️](https://youtube.com/shorts/8P0VB4DQFWw) 320 | 321 | ```javascript 322 | console.log(isFinite(Infinity), isNaN(Infinity)) 323 | ``` 324 | 325 | - A: `false, false` 326 | - B: `false, true` 327 | - C: `true, false` 328 | - D: `false, false` 329 | 330 |
Answer 331 |

332 | 333 | #### Answer: A 334 | 335 | The `isFinite()` function is used to determine whether a given value is a finite 336 | number. 337 | 338 | It returns false if the value is NaN, Infinity, or -Infinity, and true if the 339 | value is a finite number. 340 | 341 | So, in this example `isFinite(Infinity)` will return false because Infinity is 342 | not a finite number. 343 | 344 | On the other hand, the isNaN() function is used to determine whether a given 345 | value is not a number (NaN). 346 | 347 | It returns true if the value is NaN, and false if the value is a number or any 348 | other data type. 349 | 350 | So, in this example `isNaN(Infinity)` will also return false because Infinity is 351 | not NaN. 352 | 353 | Therefore always use `isFinite` function instead of `isNaN` function when you 354 | want to validate if a number is finite 355 | 356 |

357 |
358 | 359 | --- 360 | 361 | ###### 10. Arrow function [▶️](https://youtube.com/shorts/P8zFS3w-wzw) 362 | 363 | ```javascript 364 | const user = { 365 | name: 'John', 366 | age: 30, 367 | getName: () => { 368 | return this.name 369 | }, 370 | getAge: function () { 371 | return this.age 372 | }, 373 | } 374 | 375 | const getName = user.getName 376 | const getAge = user.getAge 377 | 378 | console.log(getName()) 379 | console.log(getAge()) 380 | ``` 381 | 382 | - A: undefined, undefined 383 | - B: undefined, 30 384 | - C: SyntaxError 385 | - D: John, 30 386 | 387 |
Answer 388 |

389 | 390 | #### Answer: A 391 | 392 | The `getName` arrow function uses `this` keyword to refer to the object's name 393 | property, but because arrow functions have a lexical `this` binding, the value 394 | of `this` keyword inside the arrow function will be the global object which is 395 | `window` in a browser, or `global` in Node.js. 396 | 397 | Since there is no name property on the `global` object, the function returns 398 | `undefined`. 399 | 400 | The `getAge` function uses a regular function expression and correctly refers to 401 | the age property of the `user` object using `this` keyword. 402 | 403 | But when `getAge` is assigned to the `getAge` variable, it loses the reference 404 | to the `user` object, so when the function is called using `getAge()`, this will 405 | refer to the global object again, and since there is no age property on the 406 | global object, the function returns undefined. 407 | 408 |

409 |
410 | 411 | --- 412 | 413 | ###### 11. Closure [▶️](https://youtube.com/shorts/PCc7icrQw8Y) 414 | 415 | ```javascript 416 | for (var i = 0; i < 3; i++) { 417 | setTimeout(function () { 418 | console.log(i) 419 | }, 0) 420 | } 421 | ``` 422 | 423 | - A: 0, 1, 2 424 | - B: 3, 3, 3 425 | - C: undefined, undefined, undefined 426 | - D: TypeError: console is not defined 427 | 428 |
Answer 429 |

430 | 431 | #### Answer: B 432 | 433 | A closure is a function that retains access to variables in its outer scope, 434 | even after the outer function has returned. 435 | 436 | In this example, the answer is B, because the setTimeout function is 437 | asynchronous and does not execute immediately. 438 | 439 | By the time the callback function passed to setTimeout is executed, the loop has 440 | already completed and the i variable has a value of 3. 441 | 442 | Therefore, each call to console.log(i) inside the callback function will 443 | print 3. 444 | 445 | To solve this problem and print 0, 1, 2, we can use an IIFE (Immediately Invoked 446 | Function Expression) to create a new scope for each iteration of the loop. 447 | 448 | This creates a new variable j inside each IIFE, with its own copy of the current 449 | value of i at that iteration of the loop. 450 | 451 | When the callback function passed to setTimeout is executed, it has access to 452 | the j variable in its closure, which has the expected value of 0, 1, or 2 for 453 | each iteration of the loop. 454 | 455 |

456 |
457 | 458 | --- 459 | 460 | ###### 12. Curry (Level: Hard) [▶️](https://youtu.be/KYIJVlbevkg) 461 | 462 | ```javascript 463 | function add(x) { 464 | return function (y) { 465 | if (y !== undefined) { 466 | x += y 467 | return arguments.callee 468 | } else { 469 | return x 470 | } 471 | } 472 | } 473 | 474 | console.log(add(1)(2)(3)()) 475 | ``` 476 | 477 | - A: 6 478 | - B: undefined 479 | - C: ReferenceError 480 | - D: TypeError 481 | 482 |
Answer 483 |

484 | 485 | #### Answer: A 486 | 487 | The correct answer is A. The code defines a add function that takes a single 488 | argument x and returns another function that takes a single argument y. 489 | 490 | This inner function checks if y is defined. If it is defined, it adds y to x and 491 | returns a reference to itself using the arguments.callee property, which allows 492 | the function to be called recursively with the next argument. 493 | 494 | If y is not defined, it returns the current value of x. 495 | 496 | Then, the code calls add(1)(2)(3)(). This first calls add(1) with 1 as its 497 | argument, which returns a function that takes a single argument y. 498 | 499 | Then, it calls this function with 2 as its argument, which adds 2 to 1 and 500 | returns a reference to the function. 501 | 502 | Finally, it calls this function with 3 as its argument, which adds 3 to 3 and 503 | returns a reference to the function. 504 | 505 | Since no argument is passed in the last call, it returns the current value of x, 506 | which is 6. 507 | 508 | This code demonstrates a more complex example of currying in JavaScript, where 509 | the curried function returns a reference to itself, allowing it to be called 510 | recursively with the next argument. 511 | 512 |

513 |
514 | 515 | --- 516 | 517 | ###### 13. Curry (Level: Easy) [▶️](https://youtu.be/0FLxIj0TRgU) 518 | 519 | ```javascript 520 | function multiply(x) { 521 | return function (y) { 522 | return x * y 523 | } 524 | } 525 | 526 | const double = multiply(2) 527 | 528 | console.log(double(5)) 529 | ``` 530 | 531 | - A: 25 532 | - B: 10 533 | - C: undefined 534 | - D: An error will occur 535 | 536 |
Answer 537 |

538 | 539 | #### Answer: B 540 | 541 | The correct answer is B. The code defines a multiply function that takes a 542 | single argument x and returns another function that takes a single argument y. 543 | This inner function multiplies x and y and returns the result. 544 | 545 | Then, the code creates a new function double by calling multiply with 2 as its 546 | argument. The double function is now a curried function that can be called with 547 | a single argument to double its value. 548 | 549 | Finally, the code calls double with 5 as its argument, which results in 10 being 550 | logged to the console. 551 | 552 | This code demonstrates the concept of currying in JavaScript, where a function 553 | returns another function that can be partially applied with some arguments. 554 | 555 |

556 |
557 | 558 | --- 559 | 560 | ###### 14. Iterables and Iterators (Level: Hard) [▶️](https://youtu.be/-yZ53Cmltg0) 561 | 562 | Which of the following statements is true about the `next()` method of an 563 | iterator in JavaScript? 564 | 565 | - A: The next() method returns an object with properties value and done. 566 | - B: The next() method returns a boolean value indicating whether there are more 567 | items to iterate over. 568 | - C: The next() method is used to define how to access the next item in the 569 | iterable. 570 | - D: The next() method is not used in JavaScript iterators. 571 | 572 |
Answer 573 |

574 | 575 | #### Answer: A 576 | 577 | The correct answer is A. 578 | 579 | In JavaScript, an iterable is an object that defines a sequence and can be 580 | iterated over using a loop. 581 | 582 | An iterator is an object that knows how to access the elements of an iterable 583 | one at a time. 584 | 585 | An iterable object has a method with the key `Symbol.iterator`, which returns an 586 | iterator object. 587 | 588 | The iterator object has a `next()` method, which returns an object with two 589 | properties: `value`, which is the next element in the sequence, and `done`, 590 | which is a boolean indicating whether the iterator has reached the end of the 591 | sequence. 592 | 593 | Iterables are commonly used in many real-time applications while working with 594 | large datasets, or while implementing custom data structures 595 | 596 |

597 |
598 | 599 | --- 600 | 601 | ###### 15. Generator Functions [▶️](https://youtu.be/4fIKcIMo7w4) 602 | 603 | ```javascript 604 | function* counter() { 605 | let i = 0 606 | while (true) { 607 | yield i++ 608 | } 609 | } 610 | 611 | const gen = counter() 612 | 613 | console.log(gen.next().value) 614 | console.log(gen.next().value) 615 | console.log(gen.next().value) 616 | ``` 617 | 618 | What does the above code snippet output? 619 | 620 | - A: This code snippet will result in an infinite loop. 621 | - B: 1 2 3 622 | - C: 0 0 0 623 | - D: 0 1 2 624 | 625 |
Answer 626 |

627 | 628 | #### Answer: D 629 | 630 | The correct answer is D. 631 | 632 | The `counter` function is a generator function that creates an infinite loop 633 | that yields incrementing values of `i`. 634 | 635 | The `gen` variable is set to the generator function, and each call to 636 | `gen.next()` returns an object with the value property set to the next yielded 637 | value. 638 | 639 | The `console.log` statements then print the values returned by `gen.next()`. 640 | 641 | A generator function is a special type of function that can be used to control 642 | the iteration over a sequence of values. 643 | 644 | Unlike traditional functions, generator functions allow you to pause and resume 645 | their execution, and yield multiple values over time. 646 | 647 |

648 |
649 | 650 | --- 651 | 652 | ###### 16. Garbage Collection, Mark and Sweep Algorithm [▶️](https://youtu.be/QCmqefzwWlg) 653 | 654 | Which of the following scenarios could potentially cause a memory leak in 655 | JavaScript? 656 | 657 | - A: Using the Array.from() method to convert a large array into a new array. 658 | - B: Creating a circular reference between two objects that are still in use. 659 | - C: Assigning a value of null to a variable that is still in use. 660 | - D: Calling the delete operator on an object property. 661 | 662 |
Answer 663 |

664 | 665 | #### Answer: B 666 | 667 | Circular references occur when two or more objects reference each other, 668 | creating a loop that prevents the objects from being garbage collected. 669 | 670 | This can cause a memory leak if the objects are no longer needed but cannot be 671 | freed because of the circular reference. 672 | 673 | Options A, C, and D do not typically cause memory leaks in JavaScript. 674 | 675 | Garbage collection is the process of automatically freeing up memory that is no 676 | longer being used by a program. 677 | 678 | In JavaScript, the mark and sweep algorithm is commonly used for garbage 679 | collection. 680 | 681 | This algorithm works by first marking all objects in memory that are still being 682 | referenced by the program, then sweeping through and freeing up any memory that 683 | is not marked as in use. 684 | 685 |

686 |
687 | 688 | --- 689 | 690 | ###### 17. try, catch, finally [▶️](https://youtu.be/uPhf3OjPwSU) 691 | 692 | ```javascript 693 | function getData() { 694 | return new Promise((resolve, reject) => { 695 | setTimeout(() => { 696 | resolve('Data retrieved successfully') 697 | }, 1000) 698 | }) 699 | } 700 | 701 | async function main() { 702 | try { 703 | const data = await getData() 704 | console.log(data) 705 | throw new Error('Something went wrong') 706 | } catch (err) { 707 | console.log('Caught an error:', err.message) 708 | return 'Error occurred' 709 | } finally { 710 | console.log('Finally block executed.') 711 | return 'Finally block value' 712 | } 713 | } 714 | 715 | ;(async () => { 716 | console.log(await main()) 717 | })() 718 | ``` 719 | 720 | What does the above code snippet output? 721 | 722 | - A: "Data retrieved successfully", "Caught an error: Something went wrong", 723 | "Finally block executed." 724 | - B: "Data retrieved successfully", "Caught an error: Something went wrong". 725 | - C: "Data retrieved successfully", "Caught an error: Something went wrong", 726 | "Finally block executed.", "Finally block value" 727 | - D: "Caught an error: Something went wrong", "Finally block executed." 728 | - E: "Finally block executed.", "Finally block value". 729 | 730 |
Answer 731 |

732 | 733 | #### Answer: C 734 | 735 | When the code is executed, the main() function is called, which is an async 736 | function that uses await to get data from the `getData()` function. 737 | 738 | Once the data is retrieved, the `console.log(data)` statement logs "Data 739 | retrieved successfully" to the console. 740 | 741 | After that, the `throw new Error("Something went wrong")` statement throws an 742 | error. 743 | 744 | The `catch` block catches the error and logs 745 | `"Caught an error: Something went wrong"` to the console, and then returns the 746 | string `"Error occurred"`. 747 | 748 | Finally, the finally block is executed and logs `"Finally block executed."` to 749 | the console, and then returns the string `"Finally block value"`. 750 | 751 | When the `main()` function is called, it returns a promise because it is an 752 | async function. Since the `finally` block also returns a value, that value will 753 | be the final resolved value of the promise. 754 | 755 | Therefore, when `console.log(main())` is called, `"Finally block executed."` and 756 | `"Finally block value"` will be logged to the console. 757 | 758 | Try, catch, and finally are keywords used in JavaScript to handle runtime 759 | errors. 760 | 761 |

762 |
763 | 764 | --- 765 | 766 | ###### 18. Array and Traversal in array [▶️](https://youtu.be/Mefj0GDslts) 767 | 768 | ```javascript 769 | const arr = [1, 2, 3, 4, 5]; 770 | let sum = 0; 771 | for (let num of arr) { 772 | sum += num; 773 | if(sum >= 6) break; 774 | } 775 | console.log(sum); 776 | 777 | const arr2 = [1, 2, 3, 4, 5]; 778 | let sum2 = 0; 779 | arr.forEach((num) => { 780 | sum2 += num; 781 | if(sum2 >= 6) break; 782 | }); 783 | console.log(sum2); 784 | ``` 785 | 786 | What does the above code snippet output? 787 | 788 | - A: 6, 15 789 | - B: SyntaxError: Illegal break statement 790 | - C: 15, 15 791 | - D: 15, 15 792 | 793 |
Answer 794 |

795 | 796 | #### Answer: B 797 | 798 | Because `break` statement is not valid inside the callback function passed to 799 | `forEach`. 800 | 801 | `forEach` does not support early termination using the `break` statement. 802 | Therefore, an error is thrown: 803 | `"Uncaught SyntaxError: Illegal break statement".` 804 | 805 | In case of for of loop, `break` statement is allowed. 806 | 807 | To fix the issue, remove the `break` statement from forEach and it should work. 808 | 809 | In general, `for of` is recommended over `for in` or `forEach` 810 | 811 |

812 |
813 | 814 | --- 815 | 816 | ###### 19. Array Manipulation: Understanding array.push() Method in JavaScript [▶️](https://www.youtube.com/shorts/ZkaIxib4IxI) 817 | 818 | ```javascript 819 | let arr = [1, 2, 3, 4] 820 | let result = arr.push(5) 821 | console.log('result: ', result, 'arr: ', arr) 822 | ``` 823 | 824 | What does the above code snippet output? 825 | 826 | - A: result: 5 arr: [1, 2, 3, 4, 5] 827 | - B: result: 5 arr: [5, 1, 2, 3, 4] 828 | - C: result: [1, 2, 3, 4, 5] arr: [1, 2, 3, 4, 5] 829 | - D: result: [5, 1, 2, 3, 4] arr: [5, 1, 2, 3, 4] 830 | 831 |
Answer 832 |

833 | 834 | #### Answer: A 835 | 836 | The `array.push()` method in JavaScript adds one or more elements to the end of 837 | an array and returns the new length of the array. 838 | 839 | In the given code, `arr` is an array with the values `[1, 2, 3, 4]`. The 840 | `push()` method is called with the argument 5, which adds `5` to the end of the 841 | `arr` array. 842 | 843 | The `push()` method returns the new length of the array after the addition of 844 | the element(s). In this case, the new length of arr will be 5 because `5` is 845 | added to the end of the array. 846 | 847 |

848 |
849 | 850 | --- 851 | 852 | ###### 20. Array Manipulation: Understanding array.unshift() Method in JavaScript 853 | 854 | ```javascript 855 | let arr = [3, 5, 7, 9] 856 | let result = arr.unshift(1, 2) 857 | console.log('result: ', result, 'arr: ', arr) 858 | ``` 859 | 860 | What does the above code snippet output? 861 | 862 | - A: result: 6 arr: [3, 5, 7, 9, 1, 2] 863 | - B: result: 6 arr: [1, 2, 3, 5, 7, 9] 864 | - C: result: 4 arr: [1, 2, 3, 5] 865 | - D: result: [1, 2, 3, 5, 7, 9] arr: [1, 2, 3, 5, 7, 9] 866 | 867 |
Answer 868 |

869 | 870 | #### Answer: B 871 | 872 | The `array.unshift()` method in JavaScript adds one or more elements to the 873 | beginning of an array and returns the new length of the array. 874 | 875 | In the given code, `arr` is an array with the values `[3, 5, 7, 9]`. The 876 | `unshift()` method is called with the arguments 1 and 2, which adds 1 and 2 to 877 | the beginning of the `arr` array. 878 | 879 | The `unshift()` method returns the new length of the array after the addition of 880 | the element(s). In this case, the new length of `arr` will be 6 because 1 and 2 881 | are added to the beginning of the array, shifting the existing elements to the 882 | right. 883 | 884 |

885 |
886 | 887 | --- 888 | 889 | ###### 21. Array Manipulation: Understanding array.pop() Method in JavaScript 890 | 891 | ```javascript 892 | const myArray = [1, 2, 3, 4, 5] 893 | const poppedValue = myArray.pop() 894 | console.log(poppedValue) 895 | ``` 896 | 897 | What does the above code snippet output? 898 | 899 | - A: 1 900 | - B: 5 901 | - C: 'undefined' 902 | - D: An error will occur 903 | 904 |
Answer 905 |

906 | 907 | #### Answer: B 908 | 909 | The `Array.pop()` method in JavaScript removes the last element from an array 910 | and returns that element. 911 | 912 | In this case, `myArray` is an array with elements `[1, 2, 3, 4, 5]`, and 913 | `myArray.pop()` is called, which removes the element 5 from the array and 914 | returns it. 915 | 916 |

917 |
918 | 919 | --- 920 | 921 | ###### 22. Array Manipulation: Understanding array.shift() Method in JavaScript 922 | 923 | ```javascript 924 | const arr = [10, 20, 30, 40, 50] 925 | const removedElement = arr.shift() 926 | console.log('removedElement: ', removedElement, 'arr: ', arr) 927 | ``` 928 | 929 | What does the above code snippet output? 930 | 931 | - A: removedElement: 10 arr: [20, 30, 40, 50] 932 | - B: removedElement: 50 arr: [10, 20, 30, 40] 933 | - C: removedElement: 10 arr: [10, 20, 30, 40, 50] 934 | - D: removedElement: [20, 30, 40, 50] arr: [20, 30, 40, 50] 935 | 936 |
Answer 937 |

938 | 939 | #### Answer: A 940 | 941 | The `Array.shift()` method removes the first element from the `arr` array, which 942 | is `10`, and returns it. The resulting `arr` array will then be 943 | `[20, 30, 40, 50]`. 944 | 945 | So, option A is the correct answer as it reflects the correct value of 946 | `removedElement` and the updated state of `arr` after `Array.shift()` is called. 947 | Option B is incorrect as it states that `removedElement` will be 50, which is 948 | not true. Option C is also incorrect as it state that `arr` remains unchanged, 949 | which is not accurate. Option D is slightly confusing as it states that 950 | `Array.shift()` returns the array, which is not true. 951 | 952 |

953 |
954 | 955 | --- 956 | 957 | ###### 23. Array Manipulation: Understanding array.splice() Method in JavaScript 958 | 959 | ```javascript 960 | let arr = [1, 2, 3, 4, 5] 961 | let removed = arr.splice(1, 2, 'a', 'b') 962 | console.log('removed:', removed, 'arr: ', arr) 963 | ``` 964 | 965 | What does the above code snippet output? 966 | 967 | - A: removed: [1, 2] arr: [a, b, 3, 4, 5] 968 | - B: removed: [2, 3] arr: [1, 'a', 'b', 4, 5] 969 | - C: removed: [2, 3, 'a', 'b'] arr: [1, 4, 5] 970 | - D: removed: [1, 2] arr: [3, 4, 5] 971 | 972 |
Answer 973 |

974 | 975 | #### Answer: B 976 | 977 | The `Array.splice()` method is used to modify an array by adding, removing, or 978 | replacing elements. 979 | 980 | In this case, the code snippet uses `arr.splice(1, 2, 'a', 'b')`, which starts 981 | from index 1 (removing 2 elements) and inserts the elements `a` and `b` in their 982 | place. The elements that are removed (i.e., 2 and 3) are returned and assigned 983 | to the variable removed. After execution, removed will be `[2, 3]` and `arr` 984 | will be `[1, 'a', 'b', 4, 5]`. Option C is incorrect as it includes the inserted 985 | elements in the removed array, which is not accurate. Option D is also incorrect 986 | as it mentions the incorrect elements that are removed from the array. 987 | 988 |

989 |
990 | 991 | --- 992 | 993 | ###### 24. JavaScript Array Search Methods - Array.indexOf(), Array.lastIndexOf(), and Array.includes() 994 | 995 | ```javascript 996 | const fruits = ['apple', 'banana', 'orange', 'grape', 'apple', 'kiwi'] 997 | const index = fruits.indexOf('orange') 998 | const lastIndex = fruits.lastIndexOf('apple') 999 | const result = fruits.includes('grape') 1000 | console.log('index: ', index, 'lastIndex: ', lastIndex, 'result: ', result) 1001 | ``` 1002 | 1003 | What does the above code snippet output? 1004 | 1005 | - A: index: 2, lastIndex: 4, result: true 1006 | - B: index: 3, lastIndex: 0, result: false 1007 | - C: index: 2, lastIndex: 4, result: false 1008 | - D: index: -1, lastIndex: 4, result: true 1009 | 1010 |
Answer 1011 |

1012 | 1013 | #### Answer: A 1014 | 1015 | The `Array.indexOf()` method searches for the index of the first occurrence of 1016 | the specified value in the array fruits. In this case, "orange" is found at 1017 | index 2, so `index` will be 2. 1018 | 1019 | The `Array.lastIndexOf()` method searches for the index of the last occurrence 1020 | of the specified value in the array fruits. In this case, "apple" appears twice 1021 | in the array and its last occurrence is at index 4, so `lastIndex` will be 4. 1022 | 1023 | On the other hand, the `Array.includes()` method checks if the specified value 1024 | "grape" exists in the array fruits, and since "grape" is present in the array, 1025 | `result` will be true. 1026 | 1027 |

1028 |
1029 | 1030 | --- 1031 | 1032 | ###### 25. JavaScript Advanced Array Search Methods - Array.find(), Array.findIndex(), and Array.filter() 1033 | 1034 | ```javascript 1035 | function isDivisibleBy7(num) { 1036 | return num % 7 == 0 1037 | } 1038 | 1039 | const nums = [28, 7, 3, 29, 15, 1, 2, 23] 1040 | const filterResult = nums.filter(isDivisibleBy7) 1041 | const findResult = nums.find(num => num < 10) 1042 | const findIndexResult = nums.findIndex(num => num / 2 == 14) 1043 | 1044 | console.log( 1045 | 'filterResult:', 1046 | filterResult, 1047 | 'findResult:', 1048 | findResult, 1049 | 'findIndexResult:', 1050 | findIndexResult, 1051 | ) 1052 | ``` 1053 | 1054 | What does the above code snippet output? 1055 | 1056 | - A: filterResult: 28 findResult: 2 findIndexResult: 1 1057 | - B: filterResult: [28, 7] findResult: 2 findIndexResult: 28 1058 | - C: filterResult: 7 findResult: [1, 2, 3, 7] findIndexResult: 0 1059 | - D: filterResult: [28, 7] findResult: 7 findIndexResult: 0 1060 | 1061 |
Answer 1062 |

1063 | 1064 | #### Answer: D 1065 | 1066 | The `Array.filter()` method returns an array containing all elements for which 1067 | the function passed to it returns true. In this case, the function 1068 | `isDivisibleBy7` returns true for any number that is divisible by 7. In the 1069 | `nums` array, 7 and 28 are divisible by 7, so `nums.filter(isDivisibleBy7)` 1070 | returns [28, 7]. 1071 | 1072 | The `Array.find()` method returns the first element in the array for which the 1073 | function passed to it returns true. In this case, the function passed to it 1074 | returns true for any number less than 10. There are multiple numbers in `nums` 1075 | that are less than 10, but since `Array.find()` only returns the first for which 1076 | it is true, `nums.find((num) => num < 10)` returns 7. 1077 | 1078 | The `Array.findIndex()` method is similar to the `Array.find()` method, but 1079 | returns the index of the first element in the array for which the function 1080 | passed to it returns true, rather than the element itself. In this case, the 1081 | function passed to it returns true for 28, since the 28 / 2 == 14. 28 is in the 1082 | array `nums` and is at index 0, so `nums.find((num) => num / 2 == 14)` 1083 | returns 0. 1084 | 1085 |

1086 |
1087 | 1088 | --- 1089 | 1090 | ###### 26. Array.map() Method in JavaScript 1091 | 1092 | ```javascript 1093 | const numbers = [1, 2, 3, 4, 5] 1094 | const doubledNumbers = numbers.map(num => num * 2) 1095 | console.log(doubledNumbers) 1096 | ``` 1097 | 1098 | What does the above code snippet output? 1099 | 1100 | - A: [1, 2, 3, 4, 5] 1101 | - B: [2, 4, 6, 8, 10] 1102 | - C: [2, 4, 6, 8, 10, 12] 1103 | - D: [1, 4, 9, 16, 25] 1104 | 1105 |
Answer 1106 |

1107 | 1108 | #### Answer: B 1109 | 1110 | The `Array.map()` method in JavaScript creates a new array by applying a 1111 | provided function to each element of the original array. 1112 | 1113 | In this case, the provided function `num => num * 2` multiplies each number in 1114 | the numbers array by 2, resulting in a new array `[2, 4, 6, 8, 10]`. 1115 | 1116 |

1117 |
1118 | 1119 | --- 1120 | 1121 | ###### 27. Array.reduce() Method in JavaScript 1122 | 1123 | ```javascript 1124 | const numbers = [1, 2, 3, 4, 5] 1125 | const sum = numbers.reduce((acc, val) => acc + val) 1126 | console.log(sum) 1127 | ``` 1128 | 1129 | What does the above code snippet output? 1130 | 1131 | - A: 1 1132 | - B: 15 1133 | - C: NaN 1134 | - D: undefined 1135 | 1136 |
Answer 1137 |

1138 | 1139 | #### Answer: B 1140 | 1141 | `Array.reduce()` takes an array and "reduces" it to a single value by repeatedly 1142 | applying a function to each element and keeping track of the accumulated result. 1143 | It's commonly used for tasks such as summing up an array of numbers, finding the 1144 | maximum value, or concatenating an array of strings into a single string. 1145 | 1146 | In this case, the reduce() method takes a callback function that is executed for 1147 | each element of the array. The callback function takes two parameters, `acc` and 1148 | `val`, which represent the accumulator and the current value of the array, 1149 | respectively. 1150 | 1151 | Inside the callback function, the current value of the array is added to the 1152 | accumulator and the result is returned. The `reduce()` method updates the value 1153 | of the accumulator with each iteration until it has iterated over all the 1154 | elements of the array. 1155 | 1156 | Finally, the `reduce()` method returns the final value of the accumulator, which 1157 | is the sum of all the numbers in the array, that is 15. 1158 | 1159 |

1160 |
1161 | 1162 | --- 1163 | 1164 | ###### 28. Array.reduceRight() Method in JavaScript 1165 | 1166 | ```javascript 1167 | const arr = [1, 2, 3, 4] 1168 | const result = arr.reduceRight((acc, curr) => acc + curr) 1169 | console.log(result) 1170 | ``` 1171 | 1172 | What does the above code snippet output? 1173 | 1174 | - A: 10 1175 | - B: 11 1176 | - C: 12 1177 | - D: 13 1178 | 1179 |
Answer 1180 |

1181 | 1182 | #### Answer: A 1183 | 1184 | The `reduceRight()` method is similar to the `reduce()` method, except that it 1185 | starts reducing the array from the rightmost element to the leftmost element. 1186 | The `reduceRight()` method applies a function against an accumulator and each 1187 | value of the array (from right-to-left) to reduce it to a single value. 1188 | 1189 | In the given code snippet, the `arr` array contains the values `[1, 2, 3, 4]`. 1190 | The `reduceRight()` method is called on this array with a callback function that 1191 | adds the accumulator `acc` with the current element `curr`. 1192 | 1193 | In the first iteration, the `curr` value will be `4`, and the acc value will be 1194 | `undefined`, since no initial value is provided. Therefore, the result of the 1195 | first iteration will be `4`. 1196 | 1197 | In the second iteration, the `curr` value will be `3`, and the `acc` value will 1198 | be the result of the previous iteration, which is `4`. Therefore, the result of 1199 | the second iteration will be `7`. 1200 | 1201 | In the third iteration, the `curr` value will be `2`, and the `acc` value will 1202 | be the result of the previous iteration, which is `7`. Therefore, the result of 1203 | the third iteration will be `9`. 1204 | 1205 | In the fourth and final iteration, the `curr` value will be `1`, and the `acc` 1206 | value will be the result of the previous iteration, which is `9`. Therefore, the 1207 | result of the fourth iteration will be `10`. 1208 | 1209 | Therefore, the final output of the code will be `10`. Hence, the correct option 1210 | is A. 1211 | 1212 |

1213 |
1214 | 1215 | --- 1216 | 1217 | ###### 29. Array.sort() Method in JavaScript 1218 | 1219 | ```javascript 1220 | const arr = ['Centauri', 3.14159, 'canine', 11235, undefined] 1221 | const result = arr.sort() 1222 | console.log(result) 1223 | ``` 1224 | 1225 | What does the above code snippet output? 1226 | 1227 | - A: [ 3.14159, 11235, 'Centauri', 'canine', undefined ] 1228 | - B: [ undefined, 11235, 3.14159, 'Centauri', 'canine' ] 1229 | - C: [ 11235, 3.14159, 'canine', 'Centauri', undefined ] 1230 | - D: [ 11235, 3.14159, 'Centauri', 'canine', undefined ] 1231 | 1232 |
Answer 1233 |

1234 | 1235 | #### Answer: D 1236 | 1237 | By default the `sort()` method sorts elements by character so 11235 comes before 1238 | 3.14159 because 1 comes before 3. 1239 | 1240 | Words and letters are sorted alphabetically by ASCII code so "Centauri" which 1241 | starts with an uppercase C (ASCII code 67) sorts before "canine" which starts 1242 | with a lowercase c (ASCII code 99). 1243 | 1244 | Undefined elements always sort to the end of an array. 1245 | 1246 | Thus, the final output of the code will be [ 11235, 3.14159, 'Centauri', 1247 | 'canine', undefined ] which is option D. 1248 | 1249 |

1250 |
1251 | 1252 | --- 1253 | 1254 | ###### 30. Destructuring an array in JavaScript 1255 | 1256 | ```javascript 1257 | let numbers = [1, 2, 3, undefined, 6, 7, 8, 9] 1258 | 1259 | let [a, , b, c = 2, ...rest] = numbers 1260 | 1261 | console.log(a, b, c, rest) 1262 | ``` 1263 | 1264 | What does the above code snippet output? 1265 | 1266 | - A. 1 undefined 2 [ 6, 7, 8, 9 ] 1267 | - B. 1 3 2 [ 6, 7, 8, 9 ] 1268 | - C. 1 undefined 3 [ 6, 7, 8, 9 ] 1269 | - D. 1 3 2 undefined 1270 | 1271 |
Answer 1272 |

1273 | 1274 | #### Answer: B 1275 | 1276 | With Array Destructuring it is possible to unpack certain values from an array 1277 | into individual variables. The values we created in the left hand side 1278 | (`a, b, c, rest`) correspond to the values and the order of the array we 1279 | assigned in the right hand side (`numbers`). 1280 | 1281 | - The variable `a` corresponds to the first element of the array, which is `1`. 1282 | 1283 | - Since we did not specify a variable for the next value `2`, the value is not 1284 | taken into account in the evaluation and is skipped. 1285 | 1286 | - The variable `b` corresponds to the third element of the array, which is `3`. 1287 | 1288 | - It is possible to set default values for the variables if the element in the 1289 | array is `undefined`. Since the fourth element in the array is `undefined`, 1290 | the variable `c` has the default value `2`. 1291 | 1292 | - With the spread operator (`...`) we can assign the remaining values of the 1293 | array to a variable. Since the values `[ 6, 7, 8, 9 ]` are the remaining 1294 | values of the array, they are assigned to the variable `rest`. 1295 | 1296 | Therefore, the final result is: `1 3 2 [ 6, 7, 8, 9 ]`, which is option B. 1297 | 1298 |

1299 |
1300 | 1301 | --- 1302 | 1303 | ###### 31. Date() in JavaScript 1304 | 1305 | ```javascript 1306 | const date1 = new Date() 1307 | const date2 = new Date('1995-12-17T05:10:00') 1308 | const date3 = new Date('1995-10-15T08:12:15+02:00') 1309 | 1310 | console.log(date1, '', date2, '', date3) 1311 | ``` 1312 | 1313 | What does the above code snippet output? 1314 | 1315 | - A: current date, 1995-10-17T04:10:00.000Z, 1994-10-15T06:12:15.000Z 1316 | - B: current date, 1995-12-17T04:10:00.000Z, 1995-10-15T06:12:15.000Z 1317 | - C: current date, 1995-08-17T04:10:00.000Z, 1995-10-15T06:12:15.000Z 1318 | 1319 |
Answer 1320 |

1321 | 1322 | #### Answer: B 1323 | 1324 | `new Date()` will return the current date and time followed by the two specified 1325 | dates in the format "YYYY-MM-DDTHH:MM:SS.sssZ", where "Z" represents the UTC 1326 | time zone offset. 1327 | 1328 | `YYYY-MM-DDTHH:mm:ss.sssZ` is a format used to represent dates and times in the 1329 | ISO 8601 standard. It consists of the following components: 1330 | 1331 | - `YYYY`: Four-digit year (0000 to 9999), or as an expanded year with + or - 1332 | followed by six digits. The sign is required for expanded years. -000000 is 1333 | explicitly disallowed as a valid year. 1334 | - `MM`: Two-digit month (01 = January, 02 = February, and so on). It defaults 1335 | to 01. 1336 | - `DD`: Two-digit day of the month (01 to 31) 1337 | - `T`: A separator indicating the start of the time component 1338 | - `HH`: Two-digit hour of the day in 24-hour format (00 to 23). As a special 1339 | case, 24:00:00 is allowed, and is interpreted as midnight at the beginning of 1340 | the next day. Defaults to 00. 1341 | - `mm`: Two-digit minute of the hour (00 to 59). Defaults to 00. 1342 | - `ss`: Two-digit second of the minute (00 to 59). Defaults to 00. 1343 | - `.sss`: Millisecond component (000 to 999). Defaults to 000. 1344 | - `Z`: A suffix indicating that the time is in UTC (Coordinated Universal Time), 1345 | with no offset. It can either be the literal character Z (indicating UTC), 1346 | or + or - followed by HH:mm, the offset in hours and minutes from UTC. 1347 | 1348 |

1349 |
1350 | 1351 | --- 1352 | 1353 | ###### 32. Date methods in JavaScript 1354 | 1355 | ```javascript 1356 | const date = new Date('Mart 15, 1975 23:15:30') 1357 | date.setMinutes(10) 1358 | date.setUTCDate(5) 1359 | 1360 | console.log( 1361 | 'Minutes:' + date.getMinutes() + ',', 1362 | '', 1363 | 'Year:' + date.getFullYear() + ',', 1364 | '', 1365 | 'UTCDate:' + date.getUTCDate(), 1366 | ) 1367 | ``` 1368 | 1369 | What does the above code snippet output? 1370 | 1371 | - A: Minutes:10, Year:1975, UTCDate:5 1372 | - B: Minutes:15, Year:1975, UTCDate:5 1373 | - C: Minutes:15, Year:1975, UTCDate:15 1374 | - D: Minutes:10, Year:1975, UTCDate:15 1375 | 1376 |
Answer 1377 |

1378 | 1379 | #### Answer: A 1380 | 1381 | The provided code creates a Date object initialized with the date and time of 1382 | "March 15, 1975 23:15:30". 1383 | 1384 | Then, it modifies the minutes and UTC date of the date object using the 1385 | `setMinutes()` and `setUTCDate()` methods, respectively. 1386 | 1387 | Finally, it logs the updated values of minutes, year, and UTC date using 1388 | `console.log()`. 1389 | 1390 | After modifying the minutes to 10 using `setMinutes(10)`, the `getMinutes()` 1391 | method returns the updated value of 10. 1392 | 1393 | After modifying the UTC date to 5 using `setUTCDate(5)`, the `getUTCDate()` 1394 | method returns the updated value of 5. 1395 | 1396 | The `getFullYear()` method returns the unchanged year, which is 1975. 1397 | 1398 |

1399 |
1400 | 1401 | --- 1402 | 1403 | ###### 33. Time Methods in Javascript 1404 | 1405 | ```javascript 1406 | const date1 = new Date('2023-5-1') 1407 | const next_us_election = new Date('2024-11-5') 1408 | const difference_in_time = next_us_election.getTime() - date1.getTime() 1409 | const difference_in_days = difference_in_time / (1000 * 3600 * 24) 1410 | console.log(parseInt(difference_in_days, 10) + ' Days') 1411 | ``` 1412 | 1413 | What does the above code snippet output? 1414 | 1415 | - A: 490 Days 1416 | - B: 554 Days 1417 | - C: 560 Days 1418 | - D: 530 Days 1419 | 1420 |
Answer 1421 |

1422 | 1423 | #### ANSWER: B 1424 | 1425 | The code calculates the difference in days between the date "2023-5-1" and the 1426 | next US election date "2024-11-5". It uses the `Date` object to create two 1427 | dates: `date1` represents May 1, 2023, and `next_us_election` represents 1428 | November 5, 2024. 1429 | 1430 | The `getTime()` method is used to get the time value in milliseconds for each 1431 | date. By subtracting the time value of `date1` from `next_us_election`, we get 1432 | the time difference in milliseconds. 1433 | 1434 | To convert the time difference from milliseconds to days, we divide it by the 1435 | number of milliseconds in a day (1000 _ 3600 _ 24). The result is stored in the 1436 | variable `difference_in_days`. 1437 | 1438 | Finally, the `parseInt()` function is used to convert the difference_in_days 1439 | value to an integer, and the result is logged to the console along with the 1440 | "Days" string. The output will be "554 Days". 1441 | 1442 |

1443 |
1444 | 1445 | --- 1446 | 1447 | ###### 34. Object Literals in Javascript 1448 | 1449 | ```javascript 1450 | let person = { 1451 | name: 'John', 1452 | age: 30, 1453 | hobbies: ['reading', 'traveling', 'cooking'], 1454 | address: { 1455 | street: '123 Main St', 1456 | city: 'New York', 1457 | state: 'NY', 1458 | }, 1459 | sayHello: function () { 1460 | console.log('Hello, my name is ' + this.name) 1461 | }, 1462 | } 1463 | 1464 | console.log(person.name) 1465 | console.log(person.hobbies[1]) 1466 | console.log(person.address.city) 1467 | person.sayHello() 1468 | ``` 1469 | 1470 | What does the above code snippet output? 1471 | 1472 | - A: John, traveling, New York, Hello my name is John 1473 | - B: John, cooking, New York, Hello my name is John 1474 | - C: John, reading, New York, Hello my name is John 1475 | - D: John, traveling, New York, NY 1476 | 1477 |
Answer 1478 |

1479 | 1480 | #### ANSWER: A 1481 | 1482 | The code defines an object literal `person` with properties such as `name`, 1483 | `age`, `hobbies`, and `address`, and a method `sayHello`. 1484 | 1485 | The `console.log()` statements print the value of `name`, the second element of 1486 | the `hobbies` array (which is "traveling"), and the value of the `city` property 1487 | in the `address` object (which is "New York"). 1488 | 1489 | Finally, the method `sayHello` is called on the `person` object using dot 1490 | notation, which outputs the string "Hello, my name is John" to the console. 1491 | 1492 |

1493 |
1494 | 1495 | --- 1496 | 1497 | ###### 35. this Object 1498 | 1499 | ```javascript 1500 | function User(username) { 1501 | this.username = username 1502 | 1503 | this.updateUsername = newName => { 1504 | this.username = newName 1505 | } 1506 | } 1507 | 1508 | const user1 = new User('kirandash') 1509 | const user2 = new User('bgwebagency') 1510 | 1511 | user1.updateUsername('kirandash-website') 1512 | user2.updateUsername('bgwebagency-app') 1513 | 1514 | console.log(user1.username, user2.username) 1515 | ``` 1516 | 1517 | What does the above code snippet output? 1518 | 1519 | - A:"kirandash bgwebagency" 1520 | - B:"kirandash-website bgwebagency-app" 1521 | - C:"kirandash kirandash" 1522 | - D:"bgwebagency-app bgwebagency-app" 1523 | 1524 |
Answer 1525 |

1526 | 1527 | #### Answer: B 1528 | 1529 | The code defines a constructor function `User` that creates `user` objects with 1530 | a `username` property and an `updateUsername` method. Two `user` objects, 1531 | `user1` and `user2`, are created with initial usernames 'kirandash' and 1532 | 'bgwebagency' respectively. 1533 | 1534 | The `updateUsername` method is called on both `user1` and `user2` objects to 1535 | update their usernames. `user1`'s username is updated to 'kirandash-website', 1536 | and `user2`'s username is updated to 'bgwebagency-app'. 1537 | 1538 | Finally, the code logs the concatenation of `user1.username` and 1539 | `user2.username`, which results in the output 'kirandash-website 1540 | bgwebagency-app'. 1541 | 1542 |

1543 |
1544 | 1545 | --- 1546 | 1547 | ###### 36. call(), apply() and bind() Functions Of Javascript 1548 | 1549 | ```javascript 1550 | function greet(name) { 1551 | console.log(`Hello, ${name}! Welcome to ${this.location}.`) 1552 | } 1553 | 1554 | const person = { 1555 | location: 'New York', 1556 | } 1557 | 1558 | greet.call(person, 'John') 1559 | greet.apply(person, ['Alex']) 1560 | const greetPerson = greet.bind(person) 1561 | greetPerson('Thomas') 1562 | ``` 1563 | 1564 | What does the above code snippet output? 1565 | 1566 | - A: Hello, Thomas! Welcome to New York , Hello, Alex! Welcome to New York , 1567 | Hello, Alex! Welcome to New York. 1568 | - B: Hello, John! Welcome to New York , Hello, Alex! Welcome to New York , 1569 | Hello, Thomas! Welcome to New York. 1570 | - C: Hello, Alex! Welcome to New York , Hello, Thomas! Welcome to New York , 1571 | Hello, John! Welcome to New York. 1572 | - D: None Of The Above 1573 | 1574 |
Answer 1575 |

1576 | 1577 | #### ANSWER: B 1578 | 1579 | The `call` function is used to invoke the `greet` function with the `person` 1580 | object as the context (the value of `this`) and `'John'` as the argument. 1581 | 1582 | The `apply` function is used to invoke the `greet` function with the `person` 1583 | object as the context (the value of `this`) and an array ['Alex'] as the 1584 | arguments. 1585 | 1586 | The `bind` function is used to create a new function `greetPerson` with the 1587 | `person` object as the bound context (the value of `this`). 1588 | 1589 | In summary, the code demonstrates how `call`, `apply`, and `bind` can be used to 1590 | invoke a function with a specific context and arguments 1591 | 1592 |

1593 |
1594 | 1595 | --- 1596 | 1597 | ###### 37. class, class expression and static members 1598 | 1599 | ```javascript 1600 | class Animal { 1601 | constructor(name) { 1602 | this.name = name 1603 | } 1604 | static makeSound() { 1605 | console.log('Generic animal sound') 1606 | } 1607 | sayName() { 1608 | console.log(`My name is ${this.name}`) 1609 | } 1610 | } 1611 | 1612 | const a1 = new Animal('Lion') 1613 | const a2 = new Animal('Time') 1614 | 1615 | Animal.makeSound() 1616 | a1.makeSound() 1617 | a2.makeSound() 1618 | ``` 1619 | 1620 | What does the above code snippet output? 1621 | 1622 | - A. "Generic animal sound", "TypeError", "TypeError" 1623 | - B. "Generic animal sound", "Generic animal sound", "Generic animal sound" 1624 | - C. "TypeError", "TypeError", "TypeError" 1625 | - D. "TypeError", "Generic animal sound", "Generic animal sound" 1626 | 1627 |
Answer 1628 |

1629 | 1630 | #### Answer: A 1631 | 1632 | The static method `makeSound()` is defined on the `Animal` class, and is 1633 | accessible directly through the class itself, i.e., `Animal.makeSound()`. This 1634 | will output `"Generic animal sound"` to the console. 1635 | 1636 | However, when we try to call `makeSound()` on an instance of the Animal class 1637 | `(a1.makeSound() and a2.makeSound())`, we get a TypeError, because static 1638 | methods can only be accessed through the class itself and not through its 1639 | instances. 1640 | 1641 |

1642 |
1643 | 1644 | --- 1645 | 1646 | ###### 38. for Inheritance, Subclassing and Extending built in class (Level: Hard) 1647 | 1648 | ```javascript 1649 | function Animal(name) { 1650 | this.name = name 1651 | } 1652 | 1653 | Animal.prototype.eat = function () { 1654 | console.log(this.name + ' is eating.') 1655 | } 1656 | 1657 | function Dog(name) { 1658 | Animal.call(this, name) 1659 | } 1660 | 1661 | Dog.prototype = Object.create(Animal.prototype) 1662 | Dog.prototype.constructor = Dog 1663 | 1664 | Dog.prototype.bark = function () { 1665 | console.log(this.name + ' is barking.') 1666 | } 1667 | 1668 | function CustomArray() { 1669 | Array.call(this) 1670 | } 1671 | 1672 | CustomArray.prototype = Object.create(Array.prototype) 1673 | CustomArray.prototype.constructor = CustomArray 1674 | 1675 | CustomArray.prototype.sum = function () { 1676 | return this.reduce((acc, val) => acc + val, 0) 1677 | } 1678 | 1679 | var dog = new Dog('Buddy') 1680 | dog.eat() 1681 | dog.bark() 1682 | 1683 | var numbers = new CustomArray() 1684 | numbers.push(1, 2, 3, 4, 5) 1685 | console.log(numbers.sum()) 1686 | ``` 1687 | 1688 | What will be the output of the following code 1689 | 1690 | - A: Buddy is eating Buddy is barking 15 1691 | - B: Buddy is eating Buddy is eating 12 1692 | - C: Buddy is barking Buddy is eating 9 1693 | - D: Buddy is barking Buddy is barking 10 1694 | 1695 |
Answer 1696 |

1697 | 1698 | #### Answer: A 1699 | 1700 | Explanation: In this example, we have a base class called `Animal` that defines a constructor and an `eat()` method. The subclass `Dog` extends the `Animal` class and adds its own constructor, `bark()` method, and a specific property `breed`. 1701 | 1702 | Furthermore, we extend the built-in `Array` class using the `class` syntax to 1703 | create a `CustomArray` class. The `CustomArray` class adds a custom method 1704 | called `sum()` that calculates the sum of the array elements. 1705 | 1706 | In the usage section, we create an instance of `Dog` named `dog` with the name 1707 | "Buddy" . We can call the inherited `eat()` method from the `Animal` class, the 1708 | `bark()` method defined in the `Dog` class. 1709 | 1710 | Additionally, we create an instance of `CustomArray` called `numbers` and add 1711 | some numbers to it. We can call the custom `sum()` method, which is added to the 1712 | built-in `Array` class through subclassing. 1713 | 1714 | This example showcases inheritance, subclassing, and extending a built-in class 1715 | in JavaScript, illustrating how classes can be extended and customized to add 1716 | additional functionality. 1717 | 1718 |

1719 |
1720 | 1721 | --- 1722 | 1723 | ###### 39. Destructuring Object Literal 1724 | 1725 | ```javascript 1726 | const person = { 1727 | name: 'John', 1728 | age: 30, 1729 | city: 'New York', 1730 | } 1731 | 1732 | const { name, age, city } = person 1733 | 1734 | console.log(name) 1735 | console.log(age) 1736 | console.log(city) 1737 | ``` 1738 | 1739 | What will be the output of the following code 1740 | 1741 | - A: John 30 New York 1742 | - B: John 30 John 1743 | - C: New York 30 John 1744 | - D: None of the above 1745 | 1746 |
Answer 1747 |

1748 | 1749 | #### Answer: A 1750 | 1751 | In the code above, we have an object literal called `person` with properties `name`, `age`, and `city`. We then use object destructuring to extract those properties into separate variables (`name`, `age`, and `city`). After destructuring, we can use these variables to access the corresponding values from the object. 1752 | 1753 |

1754 |
1755 | 1756 | --- 1757 | 1758 | ###### 40. JavaScript Modules, Import, and Export in ES6 1759 | 1760 | Consider the following code snippet: 1761 | 1762 | ```javascript 1763 | // module.mjs 1764 | export const PI = 3.14159 1765 | 1766 | export function calculateArea(radius) { 1767 | return PI * radius * radius 1768 | } 1769 | 1770 | export default function calculateCircumference(radius) { 1771 | return 2 * PI * radius 1772 | } 1773 | 1774 | // script.mjs 1775 | import calculateCircumference, { PI, calculateArea } from './module.mjs' 1776 | 1777 | console.log(PI) // Output: ________ 1778 | console.log(calculateArea(5)) // Output: ________ 1779 | console.log(calculateCircumference(5)) // Output: ________ 1780 | ``` 1781 | 1782 | What will be the output of the console.log statements in the code above? 1783 | 1784 | Options: 1785 | 1786 | - A. Output: `3.14159`, `78.53975`, `31.4159` 1787 | - B. Output: `3.14159`, `78.53975`, `62.8318` 1788 | - C. Output: `3.14159`, `78.53975`, `NaN` 1789 | - D. Output: `3.14159`, `NaN`, `62.8318` 1790 | 1791 |
Answer 1792 |

1793 | 1794 | #### Answer: B 1795 | 1796 | The `module.js` file exports three entities: 1797 | 1798 | 1. `PI` is a named export, exported using the `export` keyword. 1799 | 2. `calculateArea` is a named export, exported using the `export` keyword. 1800 | 3. `calculateCircumference` is the default export, exported using the 1801 | `export default` syntax. 1802 | 1803 | In the `main.js` file, we import `PI` and `calculateArea` as named exports using 1804 | the destructuring assignment syntax. We also import `calculateCircumference` as 1805 | the default export. The import statements reference the `module.js` file using 1806 | the relative file path `./module.js`. 1807 | 1808 | The outputs of the `console.log` statements will be: 1809 | 1810 | - `console.log(PI)` will output `3.14159` since we imported the named export 1811 | `PI`. 1812 | - `console.log(calculateArea(5))` will output `78.53975` since we imported the 1813 | named export `calculateArea` and called the function with a radius of 5. 1814 | - `console.log(calculateCircumference(5))` will output `62.8318` since we 1815 | imported the default export `calculateCircumference` and called the function 1816 | with a radius of 5. 1817 |

1818 |
1819 | 1820 | --- 1821 | 1822 | ###### 41. Named Import and Export 1823 | 1824 | Consider the following code snippet: 1825 | 1826 | ```javascript 1827 | // foo.js 1828 | function foo() { 1829 | console.log(`Foo`) 1830 | } 1831 | 1832 | export { foo } 1833 | ``` 1834 | 1835 | What is the correct Syntax to import the function `foo`? 1836 | 1837 | Options: 1838 | 1839 | - A. `import foo from "./foo"` 1840 | - B. `import foo as FooFunction from "./foo"` 1841 | - C. `import { foo } from "./foo"` 1842 | - D. `import { foo } from "./bar"` 1843 | 1844 |
Answer 1845 |

1846 | 1847 | #### Answer: C 1848 | 1849 | Named exports are imported into different files with braces and must be imported 1850 | with the name of the object, function or variable that was exported. In this 1851 | example, a function with the name `foo` is exported from the file `foo.js`. 1852 | Accordingly, the correct expression is: `import { foo } from "./foo"`. 1853 | 1854 |

1855 |
1856 | 1857 | --- 1858 | 1859 | ###### 42. Default Import Export (Level: Medium) 1860 | 1861 | In JavaScript, when importing a default export from a module, which syntax 1862 | correctly assigns an alias "myAlias" to the default import? 1863 | 1864 | - A: import default as myAlias from 'module'; 1865 | - B: import myAlias from 'module'; 1866 | - C: import { default as myAlias } from 'module'; 1867 | - D: Both option B and C 1868 | 1869 |
Answer 1870 |

1871 | 1872 | #### Answer: D: Both option B and C. 1873 | 1874 | Explanation: Both option B and C are valid syntaxes for importing a default export from a module and assigning it an alias. The difference between the two syntaxes is that option B does not use the { default as myAlias } syntax. This means that the default export will be imported under the name myAlias, rather than the name default. 1875 | 1876 | Here is an example of how to use the option B syntax:{import myAlias from 'module';},This will import the default export from the module module and assign it the name myAlias. You can then use the myAlias variable to access the default export from the module module. 1877 | Here is an example of how to use the option C syntax:{import { default as myAlias } from 'module';},This will import the default export from the module module and assign it the alias myAlias. You can then use the myAlias alias to access the default export from the module module. 1878 | 1879 | The choice of which syntax to use is up to you. The option B syntax is simpler, 1880 | but it can lead to collisions if there is already a variable named myAlias in 1881 | the current scope. The option C syntax is more verbose, but it avoids 1882 | collisions. 1883 | 1884 |

1885 |
1886 | 1887 | --- 1888 | 1889 | ###### Misc 1. JavaScript JSON (Level: Medium) 1890 | 1891 | Which method is used to convert a JavaScript object to a JSON string while 1892 | preserving data types like Dates and RegEx? 1893 | 1894 | - A: `JSON.stringify()` 1895 | - B: `JSON.stringify()` with a custom replacer function 1896 | - C: `JSON.toTypedString()` 1897 | - D: There is no built-in method; you need to manually convert data types before 1898 | using `JSON.stringify()` 1899 | 1900 |
Answer 1901 |

1902 | 1903 | #### Answer: B `JSON.stringify()` with a custom replacer function. 1904 | 1905 | Explanation: The `JSON.stringify()` method can be used to convert a JavaScript 1906 | object to a `JSON` string. However, by default, it will not preserve data types 1907 | like `Dates` and `RegEx`. To preserve these data types, you can use a custom 1908 | replacer function. The replacer function takes an object as input and returns a 1909 | new object with the modified values. 1910 | 1911 | The code below would show you how to use a custom replacer function to preserve 1912 | data types: 1913 | 1914 |

1915 | 1916 | ```js 1917 | function replacer(key, value) { 1918 | if (typeof value === 'Date') { 1919 | return value.toJSON() 1920 | } else if (typeof value === 'RegExp') { 1921 | return value.toString() 1922 | } else { 1923 | return value 1924 | } 1925 | } 1926 | 1927 | const object = { 1928 | date: new Date(), 1929 | regex: /some regex/, 1930 | } 1931 | 1932 | const jsonString = JSON.stringify(object, replacer) 1933 | ``` 1934 | 1935 |
1936 | 1937 | --- 1938 | --------------------------------------------------------------------------------