JavaScript Core Concepts | Fundamentals

Luisa Novaes - Aug 25 - - Dev Community

1. JavaScript Fundamentals

  • Question: What are variables in JavaScript and what are the differences between var, let, and const?

    • Variables: Containers that store data. You can declare a variable and assign values to it for use in your code.
    • var x let x const
      • var
        • Function scope: If declared inside a function, it can be accessed anywhere within that function.
        • Can be redeclared, which may lead to unexpected behavior.
      • let
        • Block scope: Within a function, it can only be accessed if within the same block { }.
        • Cannot be redeclared (i.e., declaring the same variable again).
        • Can reassign a value to the variable.
      • const
        • Block scope: Within a function, it can only be accessed if within the same block { }.
        • Cannot be redeclared.
        • Cannot reassign a value, except if it is an array or object (properties and elements can be modified).

    Note: In var, let, and const, a variable declared inside a function can only be accessed within that function. However, with var, it does not need to be within the same code block {}.

    function testVar() {
      if (true) {
        var x = 10;  // var is visible throughout the function
      }
      console.log(x);  // Works and prints 10
    }
    
    function testLet() {
      if (true) {
        let y = 20;  // let is only visible within the block {}
      }
      console.log(y);  // Error! y is not available outside the block {}
    }
    
    testVar();  // Works and prints 10
    testLet();  // Causes an error
    
  • Question: How do functions work in JavaScript? What is the difference between a regular function and an arrow function?

    • Functions: Are blocks of code designed to perform tasks. They can be called from different parts of the code to avoid repetition and ensure better organization.
Feature Regular Functions Arrow Functions
Syntax function name(args) { ... } (args) => { ... }
this Context this is dynamic and depends on how the function is called this is lexical, inherited from the scope in which it was defined
arguments Object Available within the function Not available; uses the rest operator (...args) to access arguments
Usage with new Can be used as a constructor (can be called with new) Cannot be used as a constructor (throws an error when using new)
Methods and super Can be used as a method in objects and can access super in classes Cannot access super and should not be used as an object method
Concise Syntax Typically more detailed More concise, ideal for simple functions
. . . . . .
Terabox Video Player