DEV Community

Cover image for Unlocking JavaScript: A Deep Dive into Fundamentals.πŸš€πŸš€
Dharmendra Kumar
Dharmendra Kumar

Posted on • Updated on

Unlocking JavaScript: A Deep Dive into Fundamentals.πŸš€πŸš€

1. Variables

Variables are the fundamental building blocks for storing data in JavaScript. They can be declared using var, let, or const.

Declaration and Initialization

  • var: Function-scoped or globally-scoped. Example:
  var age = 30;
Enter fullscreen mode Exit fullscreen mode
  • let: Block-scoped, recommended for mutable variables. Example:
  let name = 'Alice';
Enter fullscreen mode Exit fullscreen mode
  • const: Block-scoped, immutable variable once assigned. Example:
  const pi = 3.14;
Enter fullscreen mode Exit fullscreen mode
  • mutable object can be changed after it's created, and an immutable object can't.
  • Mutable instance is passed by reference.
  • Immutable instance is passed by value.

Hoisting

  • Variables declared with var are hoisted to the top but not initialized. Example:
  console.log(hoistedVar); // undefined
  var hoistedVar = 'I am hoisted';
Enter fullscreen mode Exit fullscreen mode

2. Math

JavaScript supports basic arithmetic operations and complex mathematical functions.

Basic Operators

  • Addition (+), Subtraction (-), Multiplication (*), Division (/). Example:
  let sum = 10 + 5; // 15
  let product = 10 * 5; // 50
Enter fullscreen mode Exit fullscreen mode

Math Object

  • Provides advanced mathematical functions. Example:
  let maxVal = Math.max(10, 20, 30); // 30
  let randomNum = Math.random(); // A random number between 0 and 1
Enter fullscreen mode Exit fullscreen mode

3. Text

Strings in JavaScript are used for storing and manipulating text.

String Methods

  • length: Returns the length of the string. Example:
  let str = "Hello, World!";
  console.log(str.length); // 13
Enter fullscreen mode Exit fullscreen mode
  • toUpperCase(), toLowerCase(): Change case. Example:
  console.log(str.toUpperCase()); // "HELLO, WORLD!"
Enter fullscreen mode Exit fullscreen mode
  • substring(): Extracts a part of the string. Example:
  console.log(str.substring(0, 5)); // "Hello"
Enter fullscreen mode Exit fullscreen mode

4. Arrays

Arrays are used to store multiple values in a single variable.

Creating Arrays

  • Use square brackets []. Example:
  let fruits = ['Apple', 'Banana', 'Cherry'];
Enter fullscreen mode Exit fullscreen mode

Array Methods

  • push(), pop(): Add/remove items from the end. Example:
  fruits.push('Orange'); // ['Apple', 'Banana', 'Cherry', 'Orange']
  fruits.pop(); // ['Apple', 'Banana', 'Cherry']
Enter fullscreen mode Exit fullscreen mode
  • shift(), unshift(): Add/remove items from the beginning. Example:
  fruits.shift(); // ['Banana', 'Cherry']
  fruits.unshift('Strawberry'); // ['Strawberry', 'Banana', 'Cherry']
Enter fullscreen mode Exit fullscreen mode
  • map(), filter(): Transform and filter arrays. Example:
  let lengths = fruits.map(fruit => fruit.length); // [10, 6]
  let shortFruits = fruits.filter(fruit => fruit.length < 7); // ['Banana']
Enter fullscreen mode Exit fullscreen mode

5. Conditionals

Control the flow of your code with conditional statements.

if, else if, else

  • Execute code based on conditions. Example:
  let num = 10;
  if (num > 10) {
    console.log("Greater than 10");
  } else if (num < 10) {
    console.log("Less than 10");
  } else {
    console.log("Equal to 10");
  }
Enter fullscreen mode Exit fullscreen mode

switch

  • Use for multiple conditions based on a single variable. Example:
  let fruit = 'Apple';
  switch (fruit) {
    case 'Banana':
      console.log('Banana is yellow');
      break;
    case 'Apple':
      console.log('Apple is red');
      break;
    default:
      console.log('Unknown fruit');
  }
Enter fullscreen mode Exit fullscreen mode

6. Loops

Loops allow repetitive tasks to be performed efficiently.

for Loop

  • Iterates a specified number of times. Example:
  for (let i = 0; i < 5; i++) {
    console.log(i);
  }
Enter fullscreen mode Exit fullscreen mode

while Loop

  • Iterates while a condition is true. Example:
  let i = 0;
  while (i < 5) {
    console.log(i);
    i++;
  }
Enter fullscreen mode Exit fullscreen mode

forEach

  • Iterates over array elements. Example:
  let numbers = [1, 2, 3];
  numbers.forEach(num => console.log(num));
Enter fullscreen mode Exit fullscreen mode

7. Functions

Functions are reusable blocks of code designed to perform a particular task.

Function Declaration

  • Define a function using function keyword. Example:
  function greet(name) {
    return `Hello, ${name}!`;
  }
  console.log(greet('Alice')); // "Hello, Alice!"
Enter fullscreen mode Exit fullscreen mode

Function Expression

  • Assign a function to a variable. Example:
  const square = function(num) {
    return num * num;
  };
  console.log(square(4)); // 16
Enter fullscreen mode Exit fullscreen mode

Arrow Functions

  • A shorter syntax for function expressions. Example:
  const add = (a, b) => a + b;
  console.log(add(2, 3)); // 5
Enter fullscreen mode Exit fullscreen mode

8. JavaScript Object Basics

Objects store collections of key-value pairs.

Creating Objects

  • Use object literals {}. Example:
  let person = {
    name: 'John',
    age: 30,
    greet: function() {
      return `Hello, my name is ${this.name}`;
    }
  };
  console.log(person.greet()); // "Hello, my name is John"
Enter fullscreen mode Exit fullscreen mode

Accessing Properties

  • Use dot notation or bracket notation. Example:
  console.log(person.name); // "John"
  console.log(person['age']); // 30
Enter fullscreen mode Exit fullscreen mode

Adding/Modifying Properties

  • Directly add or modify properties. Example:
  person.job = 'Developer';
  person.age = 31;
Enter fullscreen mode Exit fullscreen mode

9. DOM Scripting

DOM (Document Object Model) scripting allows you to interact with and manipulate HTML and CSS.

Selecting Elements

  • Use methods like getElementById(), querySelector(). Example:
  let heading = document.getElementById('main-heading');
  let paragraphs = document.querySelectorAll('p');
Enter fullscreen mode Exit fullscreen mode

Manipulating Elements

  • Change content and style. Example:
  heading.textContent = 'New Heading';
  heading.style.color = 'blue';
Enter fullscreen mode Exit fullscreen mode

10. Events

Events allow JavaScript to interact with user actions.

Event Listeners

  • Attach event handlers to elements. Example:
  let button = document.querySelector('button');
  button.addEventListener('click', function() {
    alert('Button clicked!');
  });
Enter fullscreen mode Exit fullscreen mode

Common Events

  • click, mouseover, mouseout, keydown, load. Example:
  document.addEventListener('keydown', function(event) {
    console.log(`Key pressed: ${event.key}`);
  });
Enter fullscreen mode Exit fullscreen mode

11. Async JavaScript Basics

Asynchronous programming allows your code to run without blocking other operations.

Callbacks

  • Functions passed as arguments to be executed later. Example:
  function fetchData(callback) {
    setTimeout(() => {
      callback('Data fetched');
    }, 2000);
  }

  fetchData(message => {
    console.log(message);
  });
Enter fullscreen mode Exit fullscreen mode

Promises

  • Represent eventual completion (or failure) of an asynchronous operation. Example:
  let promise = new Promise((resolve, reject) => {
    let success = true;
    if (success) {
      resolve('Operation succeeded');
    } else {
      reject('Operation failed');
    }
  });

  promise.then(message => {
    console.log(message);
  }).catch(error => {
    console.error(error);
  });
Enter fullscreen mode Exit fullscreen mode

Async/Await

  • Syntactic sugar for promises, making asynchronous code look synchronous. Example:
  async function fetchData() {
    let response = await fetch('https://api.example.com/data');
    let data = await response.json();
    console.log(data);
  }
  fetchData();
Enter fullscreen mode Exit fullscreen mode

12. Network Requests with fetch()

The fetch() API allows you to make network requests similar to XMLHttpRequest.

Making a Request

  • Fetch data from a server. Example:
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error

:', error));
Enter fullscreen mode Exit fullscreen mode

Handling Responses

  • Convert response to usable data. Example:
  fetch('https://api.example.com/data')
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then(data => console.log(data))
    .catch(error => console.error('Fetch error:', error));
Enter fullscreen mode Exit fullscreen mode

13. Working with JSON

JSON (JavaScript Object Notation) is a common data format used for exchanging data.

Parsing JSON

  • Convert JSON strings to JavaScript objects. Example:
  let jsonString = '{"name": "John", "age": 30}';
  let user = JSON.parse(jsonString);
  console.log(user.name); // "John"
Enter fullscreen mode Exit fullscreen mode

Stringifying Objects

  • Convert JavaScript objects to JSON strings. Example:
  let userObj = { name: 'Alice', age: 25 };
  let userJSON = JSON.stringify(userObj);
  console.log(userJSON); // '{"name":"Alice","age":25}'
Enter fullscreen mode Exit fullscreen mode

14. Libraries and Frameworks

JavaScript libraries and frameworks can simplify development and add powerful features.

jQuery

  • Simplifies DOM manipulation, event handling, and Ajax. Example:
  $(document).ready(function() {
    $('button').click(function() {
      alert('Button clicked!');
    });
  });
Enter fullscreen mode Exit fullscreen mode

React

  • A library for building user interfaces. Example:
  import React from 'react';
  import ReactDOM from 'react-dom';

  function App() {
    return <h1>Hello, World!</h1>;
  }

  ReactDOM.render(<App />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

Angular

  • A framework for building web applications. Example:
  import { Component } from '@angular/core';

  @Component({
    selector: 'app-root',
    template: '<h1>Hello, World!</h1>'
  })
  export class AppComponent {}
Enter fullscreen mode Exit fullscreen mode

15. Debugging JavaScript

Debugging is essential for finding and fixing errors in your code.

Console Logging

  • Use console.log() to inspect values. Example:
  let value = 42;
  console.log(value);
Enter fullscreen mode Exit fullscreen mode

Debugger Statement

  • Pause execution for debugging. Example:
  function test() {
    let x = 10;
    debugger; // Pauses here
    x += 5;
    return x;
  }
  test();
Enter fullscreen mode Exit fullscreen mode

Browser Developer Tools

  • Use tools in browsers like Chrome and Firefox to inspect, debug, and profile your code.

Example:

  • Open Developer Tools with F12 or right-click and select "Inspect". Use the "Console" tab to log messages and the "Sources" tab to set breakpoints and step through code.

Conclusion

Mastering JavaScript fundamentals equips you with the skills needed to build dynamic, interactive web applications. By understanding variables, math operations, text manipulation, arrays, conditionals, loops, functions, objects, DOM scripting, events, asynchronous programming, network requests, JSON, libraries and frameworks, and debugging techniques, you can create robust and efficient JavaScript applications. Dive into these core concepts to enhance your coding prowess and develop powerful web experiences.

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited

Switch - Use for multiple conditions based on a single variable

It is used for multiple conditions based on a single expression - which could be a single variable, but doesn't have to be.

Function declaration - Define a function using function keyword

Function expression also uses the 'function' keyword to define a function. Function declaration is use of the 'function' keyword at a place in the code where a statement is valid. Function declaration always requires a function name. The defined function will be stored in a variable with the same name as the function. Function declaration effectively declares a variable and assigns the function to it.

Function expression - Assign a function to a variable

Whilst it is true that functions defined using function expression are often stored in variables, they don't have to be - assignment is a totally separate thing. Function expression is the act of defining a function using the 'function' keyword at a place in the code where a statement would be invalid. Function names are optional when using function expression.

Collapse
 
dharamgfx profile image
Dharmendra Kumar

Thanks for your suggestion.

Collapse
 
officialphaqwasi profile image
Isaac Klutse

Nice and wonderful article but I will not recommend it for beginners. Its too precises and lacks a lot of information.
There is no need to cover a lot of topic in one post when it comes to beginners. I think letting them know what you are tell to say matters.
Right from variables, I got a lot of question running through my mind.

Collapse
 
dharamgfx profile image
Dharmendra Kumar

Thanks