JS Flashcards

Interview

1
Q

What do you understand about JavaScript?

A

JavaScript is a popular web scripting language and is used for client-side and server-side development. It enables interactive and dynamic content on websites.

It’s capable of:

  • Adding Interactivity: JavaScript makes web pages more engaging by allowing developers to create responsive elements like buttons, forms, animations, and more.
  • Manipulating Web Page Content: It can modify HTML and CSS, changing the structure and appearance of a webpage dynamically.
  • Handling Events: JavaScript can respond to user actions like clicks, keystrokes, and mouse movements to trigger specific actions or functions.
  • Data Handling: It can store and manage data, perform calculations, and interact with databases.
  • Creating Web Applications: With frameworks like React, Angular, or Vue.js, JavaScript is used to build complex and efficient web applications.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What’s the difference between JavaScript and Java?

A

JavaScript
- JavaScript is an object-oriented scripting language.
- JavaScript applications are meant to run inside a web browser.
- JavaScript does not need compilation before running the application code.

Java
- Java is an object-oriented programming language.
- Java applications are generally made for use in operating systems and virtual machines.
- Java source code needs a compiler before it can be ready to run in realtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the various data types that exist in JavaScript?

A
  • Boolean - For true and false values
  • Null - For empty or unknown values
  • Undefined - For variables that are only declared and not defined or initialized
  • Number - For integer and floating-point numbers
  • String - For characters and alphanumeric values
  • Object - For collections or complex values
  • Symbols - For unique identifiers for objects
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the difference between null and undefined?

A
  • undefined: Usually means a variable has been declared but not assigned a value, or a function without a return statement returns undefined.
  • null: Specifically set by a programmer to indicate an intentional absence of value or to clear a variable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the features of JavaScript?

A

These are the features of JavaScript:

  • Lightweight, interpreted programming language
  • Cross-platform compatible
  • Open-source
  • Object-oriented
  • Integration with other backend and frontend technologies
  • Used especially for the development of network-based applications
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the advantages of JavaScript over other web technologies?

A

These are the advantages of JavaScript:

  • Enhanced Interaction
    JavaScript adds interaction to otherwise static web pages and makes them react to users’ inputs.
  • Quick Feedback
    There is no need for a web page to reload when running JavaScript. For example, form input validation.
  • Rich User Interface
    JavaScript helps in making the UI of web applications look and feel much better.
  • Frameworks
    JavaScript has countless frameworks and libraries that are extensively used for developing web applications and games of all kinds.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are some of the built-in methods in JavaScript?

A
  • String Methods:
    length: Returns the length of a string.
    charAt(index): Returns the character at the specified index.
    toUpperCase(), toLowerCase(): Converts a string to uppercase or lowercase.
    concat(): Joins two or more strings.
    indexOf(substring), lastIndexOf(substring): Finds the index of a substring within a string.
    slice(start, end): Extracts a portion of a string.
  • Array Methods:
    push(), pop(): Add/remove elements from the end of an array.
    shift(), unshift(): Add/remove elements from the beginning of an array.
    concat(): Joins two or more arrays.
    join(separator): Joins all elements of an array into a string.
    slice(start, end): Extracts a portion of an array.
    indexOf(element), lastIndexOf(element): Finds the index of an element within an array.
    forEach(), map(), filter(), reduce(): Iterating and performing operations on array elements.
  • Object Methods:
    Object.keys(obj): Returns an array of an object’s keys.
    Object.values(obj): Returns an array of an object’s values.
    Object.entries(obj): Returns an array of an object’s key-value pairs.
  • Number Methods:
    toString(): Converts a number to a string.
    toFixed(), toPrecision(): Formats a number to a specified length or precision.
    parseInt(), parseFloat(): Parses a string and returns an integer or floating-point number.
  • Other Useful Methods:
    setTimeout(), setInterval(): Functions to execute code after a specified delay or at specified intervals.
    JSON.parse(), JSON.stringify(): Methods to convert JSON data to/from JavaScript objects.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the scopes of a variable in JavaScript?

A

The scope of a variable implies where the variable has been declared or defined in a JavaScript program. There are two scopes of a variable:

  • Global Scope
    Global variables, having global scope are available everywhere in a JavaScript code.
  • Local Scope
    Local variables are accessible only within a function in which they are defined.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the ‘this’ keyword in JavaScript?

A

The ‘this’ keyword in JavaScript refers to the currently calling object. It is commonly used in constructors to assign values to object properties.

  • Global Context:
    In the global context (outside of any function), this refers to the global object (window in browsers, global in Node.js).
  • Function Context:
    Inside a function, this refers to the global object in non-strict mode but becomes undefined in strict mode if not explicitly set or if the function is not called on any object.
  • Object Method:
    When a function is a method of an object, this refers to the object that owns the method being called.
    Constructor Context:
  • Inside a constructor function (used with new keyword to create objects), this refers to the specific instance of the object being created by that constructor.
    Explicitly Bound Context:
  • Using methods like call(), apply(), or bind() allows explicitly defining what this refers to within a function, overriding its default context.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the conventions of naming a variable in JavaScript?

A

Following are the naming conventions for a variable in JavaScript:

  • Variable names cannot be similar to that of reserved keywords. For example, var, let, const, etc.
  • Variable names cannot begin with a numeric value. They must only begin with a letter or an underscore character.
  • Variable names are case-sensitive.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is Callback in JavaScript?

A

In JavaScript, a callback is a function passed as an argument to another function to be executed later. Callbacks are commonly used in asynchronous operations or when you want a function to be executed after another function has finished its execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the difference between Function declaration and Function expression?

A
  • Function declaration
    Declared as a separate statement within the main JavaScript code .
    Can be called before the function is defined.
    function abc() {
    return 5;
    }
  • Function expression
    Created inside an expression or some other construct.
    Created when the execution point reaches it; can be used only after that.
    const greet = function() {
    return “Hello!”;
    };

var a = function abc() {
return 5;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the ways of adding JavaScript code in an HTML file?

A

There are primarily two ways of embedding JavaScript code:

  • We can write JavaScript code within the script tag in the same HTML file; this is suitable when we need just a few lines of scripting within a web page.
  • We can import a JavaScript source file into an HTML document; this adds all scripting capabilities to a web page without cluttering the code
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What do you understand about cookies?

A

A cookie is generally a small data that is sent from a website and stored on the user’s machine by a web browser that was used to access the website. Cookies are used to remember information for later use and also to record the browsing activity on a website.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How would you create a cookie?

A

Structure :
document.cookie = “key1 = value1; key2 = value2; expires = date”;

Example :
// Function to set a cookie
function setCookie(cookieName, cookieValue, expirationDays) {
const d = new Date();
d.setTime(d.getTime() + (expirationDays * 24 * 60 * 60 * 1000)); // Set expiration time

const expires = "expires=" + d.toUTCString();
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/"; }

// Usage: Set a cookie with the name “username” and value “John Doe” that expires in 7 days
setCookie(“username”, “John Doe”, 7);

Result of Example
document.cookie = “username=John Doe; expires=Thu, 17 Dec 2024 12:00:00 UTC; path=/”;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How would you read a cookie?

A

Reading a cookie using JavaScript is also very simple. We can use the document.cookie string that contains the cookies that we just created using that string.

The document.cookie string keeps a list of name-value pairs separated by semicolons, where ‘name’ is the name of the cookie, and ‘value’ is its value. We can also use the split() method to break the cookie value into keys and values.

function getCookie(cookieName) {
const name = cookieName + “=”;
const decodedCookie = decodeURIComponent(document.cookie);
const cookieArray = decodedCookie.split(‘;’);

for(let i = 0; i < cookieArray.length; i++) {
    let cookie = cookieArray[i].trim();
    if (cookie.indexOf(name) === 0) {
        return cookie.substring(name.length, cookie.length);
    }
}
return ""; }

// Usage: Read the value of the “username” cookie
const username = getCookie(“username”);
console.log(username);

17
Q

How would you delete a cookie?

A

To delete a cookie, we can just set an expiration date and time. Specifying the correct path of the cookie that we want to delete is a good practice since some browsers won’t allow the deletion of cookies unless there is a clear path that tells which cookie to delete from the user’s machine.

// Function to delete a specific cookie by name
function deleteCookie(cookieName) {
document.cookie = ${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;; // Set expiration date in the past
}

// Example: Deleting a cookie named “username”
deleteCookie(‘username’);
console.log(‘Username cookie deleted.’);

18
Q

What’s the difference between var, let and const?

A
  • var:
    Function Scoped: Variables declared with var are function-scoped. They are visible throughout the function they are declared in, regardless of block scope.
    Hoisting: Variables declared with var are hoisted to the top of their scope. This means they can be accessed before they are declared, but they will have an initial value of undefined.
    Reassignment and Redefinition: var allows both reassignment and redeclaration within the same scope.
    Example:
    var x = 10;
    if (true) {
    var x = 20; // This reassigns the outer x
    console.log(x); // Output: 20
    }
    console.log(x); // Output: 20
  • let:
    Block Scoped: Variables declared with let are block-scoped. They exist only within the block ({}) they are defined in.
    Hoisting: Variables declared with let are hoisted to the top of their block, but they are not initialized. Accessing a let variable before its declaration results in a ReferenceError.
    Reassignment: let allows variable reassignment but not redeclaration within the same scope.
    Example:
    let y = 10;
    if (true) {
    let y = 20; // This creates a new y variable within this block
    console.log(y); // Output: 20
    }
    console.log(y); // Output: 10
  • const:
    Block Scoped: Variables declared with const are block-scoped similar to let.
    Assignment and Reassignment: const is used for constants. Once assigned, a const variable cannot be reassigned or redeclared within the same scope. However, the content of a const object or array can be modified.
    Hoisting: Like let, const variables are hoisted but not initialized.
    Example:
    const z = 10;
    if (true) {
    const z = 20; // This creates a new z variable within this block
    console.log(z); // Output: 20
    }
    console.log(z); // Output: 10
19
Q

What are Closures in JavaScript?

A

closures in JavaScript refer to the ability of a function to remember and access its lexical scope, even when it’s executed outside that scope. In simpler terms, a closure is a function bundled together with references to its surrounding state (the lexical environment) at the time of its creation.

function outerFunction() {
const outerVar = ‘I am from the outer function’;

function innerFunction() {
    console.log(outerVar); // Inner function accessing outer variable
}

// Returning the inner function
return innerFunction; }

const closureExample = outerFunction(); // Assign the inner function to a variable
closureExample(); // Invoke the inner function

20
Q

What are the arrow functions in JavaScript?

A

Arrow functions, introduced in ECMAScript 6 (ES6), are a concise way of writing anonymous function expressions in JavaScript. They provide a shorter syntax compared to traditional function expressions and offer a more concise way to write functions.

const helloWorld = () => {

console.log(“hello world!”);

};

21
Q

What makes JS unique?

A
  • Functionality
  • Interactivity
  • Dynamic websites
  • User interaction
22
Q

How many ways are there to add JS into HTML?

A

Inline JS :

<body>
<button>Click Me</button>
</body>

Internal JS:
<button>Click Me</button>
<button>Click Me</button>
<button>Click Me</button>

<script>
document.querySelectorAll('.btn').forEach((item)=> {
    item.addEventListener('click', ()=>{
      alert('Hello People');
    })
  });
</script>

External JS:


23
Q

Why it is not a good practice to use inline and internal JS?

A
  • Because it breaks the separation of concerns.
  • Reduces code readability and maintainability.
  • Prevents reusability
  • Makes debugging more difficult.
24
Q

What is a statement in JS?

A

A statement is a complete and individual unit of execution ending with (;)

25
Q

What is a comment?

A

Is a text which is ignored by the JavaScript interpreter during execution, we are using it for taking notes and debugging.

26
Q

What is implicit type conversion in JS?

A

Implicit type conversion also known as type coercion, is a feature in JavaScript where the JavaScript engine automatically converts one data type to another during an operation.
let num = 10;
let str = “5”;
console.log(num + str);
Output: “105”

const value = ‘10’ - ‘23’ ===> -13
const value = ‘10’ + ‘23’ ===> 1023

27
Q

How many data types are there in JS?

A

Primitive Data Types:
These are basic, immutable data types directly operated upon by the language. There are six primitive data types in JavaScript:
- Number: Represents numeric values.
- String: Represents textual data.
- Boolean: Represents true or false values.
- Undefined: Represents an uninitialized variable.
- Null: Represents the intentional absence of any object value.
- Symbol: Introduced in ECMAScript 6 (ES6), represents a unique identifier.

let numberVar = 42;
let stringVar = ‘Hello, World!’;
let booleanVar = true;
let undefinedVar = undefined;
let nullVar = null;
let symbolVar = Symbol(‘unique’);

Object Data Types:
Objects are more complex and mutable data types. They include:
- Object: A collection of key-value pairs.
- Array: An ordered list of values.
- Function: A reusable block of code.
let objectVar = { key: ‘value’ };
let arrayVar = [1, 2, 3];
let functionVar = function() { /* code */ };

28
Q

What is the result of this ?
console.log(typeof(null));

A

Object

29
Q

What is the result of this ?
console.log(typeof(undefined));

A

undefined

30
Q

What is a function in JS?

A

In JavaScript, a function is a reusable block of code that performs a specific task or set of tasks.
We can use a function by invoking it.
By default all the functions are returning undefined.

31
Q

What is parameter in a function?

A

Parameter is a local variables or placeholders that can be used only in the function’s body not outside.

32
Q

What is the difference between parameter and argument?

A

A parameter is a variable or placeholder in a function definition.

An argument is an actual value or expression passed to a function when it is called.

33
Q

What does if(!value) expression mean?

A

The expression if (!value) is a conditional statement in JavaScript that checks if the value of the variable or expression value is falsy.

34
Q

What is interpolation?

A

Interpolation refers to the process of embedding or inserting variables or expressions into a string.
- String Concatenation:
- Template Literals

35
Q

What is the difference between find and filter?

A

filter returns an array but find return just a instance of the array.

find is returning just the first match of the condition while filter is returning all the items that match with the condition

35
Q

What is a spread operator?

A

feature introduced in ECMAScript 6 (ES6) that allows the elements of an iterable (like an array or a string) to be expanded or spread into places where multiple elements or variables are expected.
We use it for Copying and combining Arrays and Objects.

35
Q

What is a higher order function?

A

a higher-order function is a function that takes one or more functions as arguments or returns a function as its result.

function morning(name){
return Good Morning ${name.toUpperCase()}!!!!;
}

function greet(name,cb){
let myName = “Sana”;
console.log(${cb(name)}, I am ${myName});
}

greet(“Umo”,morning);