DeveloperBreeze

Section 2.1: Syntax and Basics

Tutorial 2.1.2: Variables and Constants


Variables and Constants in JavaScript

In JavaScript, variables and constants are used to store data that your program can use and manipulate. This tutorial explains how to declare, initialize, and use variables and constants effectively.


Declaring Variables

Variables in JavaScript can be declared using three keywords: var, let, and const.

  1. var (Legacy):
  • Used in older JavaScript versions but largely replaced by let and const.
  • Example:
     var message = "Hello, World!";
     console.log(message);
  1. let (Modern):
  • Preferred for declaring variables that can change value.
  • Example:
     let age = 25;
     age = 26; // Allowed
     console.log(age); // 26
  1. const (Constants):
  • Used for variables whose value should not change.
  • Example:
     const PI = 3.14;
     console.log(PI); // 3.14

Rules for Naming Variables

  1. Must start with a letter, underscore (_), or dollar sign ($).
  • Valid: name, _age, $price
  • Invalid: 1name, @value
  1. Case-sensitive:
  • age and Age are different.
  1. Avoid JavaScript reserved keywords (e.g., let, const, var).

Variable Initialization

Variables can be declared without assigning a value. Uninitialized variables are undefined.

Example:

let greeting;
console.log(greeting); // undefined

Using let and const in Practice

  1. When to Use let:
  • Use let for variables whose value may change.
  • Example:
     let score = 10;
     score += 5; // score is now 15
  1. When to Use const:
  • Use const for constants or variables that should remain unchanged.
  • Example:
     const API_KEY = "12345";
     // API_KEY = "67890"; // Error: Assignment to constant variable

Scope of Variables

  1. Block Scope (let and const):
  • Variables are accessible only within the block they are declared in.
  • Example:
     {
       let x = 10;
       console.log(x); // 10
     }
     console.log(x); // Error: x is not defined
  1. Function Scope (var):
  • Variables are accessible within the entire function they are declared in.
  • Example:
     function test() {
       var y = 20;
       console.log(y); // 20
     }
     console.log(y); // Error: y is not defined

Best Practices

  1. Use const by default; switch to let if the value needs to change.
  2. Avoid using var in modern JavaScript.
  3. Use meaningful names for variables.

Exercise

  1. Declare a variable name using let and assign it your name. Log it to the console.
  2. Declare a constant BIRTH_YEAR with your birth year. Try to change its value and note the error.

Example:

let name = "Alice";
console.log(name);

const BIRTH_YEAR = 1990;
// BIRTH_YEAR = 2000; // Error: Assignment to constant variable

Continue Reading

Discover more amazing content handpicked just for you

Tutorial
javascript

Comparison and Logical Operators

  • Logical operators evaluate left to right; ensure your conditions are correct.
  • The user must be logged in (isLoggedIn is true).
  • The user's account must not be suspended (isSuspended is false).

Dec 11, 2024
Read More
Tutorial
javascript

Arithmetic Operators

  • Modulus with Negative Numbers:
  • Be cautious, as the result can be negative.
    console.log(-10 % 3); // -1

Dec 11, 2024
Read More
Tutorial
javascript

Non-Primitive Data Types (Objects, Arrays, and Functions)

  delete person.isStudent;
  console.log(person);

Arrays are ordered collections of elements, which can be of any type.

Dec 11, 2024
Read More
Tutorial
javascript

Primitive Data Types

Used for very large integers beyond the safe range of number.

  • Syntax: Append n to the end of an integer.
  • Example:

Dec 11, 2024
Read More
Tutorial
javascript

Hello World and Comments

     /*
      This is a multi-line comment.
      It spans multiple lines.
     */
     console.log("Hello, World!");
  • Documenting code logic.
  • Temporarily disabling code during debugging.
  • Adding notes or reminders for developers.

Dec 10, 2024
Read More
Tutorial
javascript css +1

How to Create a Chrome Extension for Automating Tweets on X (Twitter)

Before diving into the code, let's set up the structure for our Chrome extension. You'll need:

Create a new folder for your project, and within it, create the following files:

Dec 10, 2024
Read More
Tutorial
php

Laravel Best Practices for Sharing Data Between Views and Controllers

   php artisan make:middleware ShareUserPreferences

Open the middleware file and share data conditionally:

Nov 16, 2024
Read More
Tutorial

Connecting a Node.js Application to an SQLite Database Using sqlite3

In this tutorial, you've learned how to integrate an SQLite database into your Node.js application using the sqlite3 package. By following the steps outlined, you've successfully:

  • Set Up: Initialized a Node.js project and installed necessary packages.
  • Connected: Established a connection to an SQLite database.
  • Created Tables: Defined and created the "accounts" table with specified columns.
  • Manipulated Data: Inserted and retrieved data from the database.
  • Ensured Security: Understood and applied best practices to protect sensitive information.

Oct 24, 2024
Read More
Tutorial
javascript

الفرق بين let و const و var في JavaScript

في JavaScript، توجد ثلاثة طرق رئيسية لإعلان المتغيرات: var و let و const. كل طريقة لها استخداماتها وقواعدها الخاصة. في هذا الدليل، سنتناول الفرق بينها بالتفصيل.

  • var هي الطريقة القديمة لتعريف المتغيرات في JavaScript وكانت تُستخدم قبل ECMAScript 6 (ES6).
  • نطاق المتغير: المتغيرات المُعلنة باستخدام var تكون ذات نطاق وظيفي أو عام (Global/Function Scope).
  • إعادة التعريف: يمكنك إعادة تعريف المتغيرات المُعلنة باستخدام var دون حدوث أخطاء.

Sep 26, 2024
Read More
Article
bash

Top 25 Nginx Web Server Best Security Practices

Remove or block the execution of unwanted file types like .php or .exe if not needed on your server.

location ~* \.(exe|sh|bat)$ {
    return 403;
}

Sep 24, 2024
Read More
Tutorial
javascript

JavaScript Tutorial for Absolute Beginners

let name = "Alice";
const age = 25;
var isStudent = true;

console.log(name, age, isStudent);
  • let is used for variables that can be reassigned.
  • const is for variables that should not be reassigned.
  • var is an older way of declaring variables and is generally not recommended for new code.

Sep 02, 2024
Read More
Tutorial
javascript

Creating a Dropdown Menu with JavaScript

// script.js
document.addEventListener('DOMContentLoaded', function () {
  const dropdownToggle = document.querySelector('.dropdown-toggle');
  const dropdownMenu = document.querySelector('.dropdown-menu');

  dropdownToggle.addEventListener('click', function (event) {
    event.preventDefault();
    dropdownMenu.style.display = dropdownMenu.style.display === 'block' ? 'none' : 'block';
  });

  document.addEventListener('click', function (event) {
    if (!dropdownToggle.contains(event.target) && !dropdownMenu.contains(event.target)) {
      dropdownMenu.style.display = 'none';
    }
  });
});

In this script:

Sep 02, 2024
Read More
Tutorial
javascript

Understanding JavaScript Classes

The extends keyword is used to create a subclass (child class) that inherits from another class (parent class).

class Animal {
  constructor(type, name) {
    this.type = type;
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super('Dog', name);
    this.breed = breed;
  }

  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog('Buddy', 'Golden Retriever');
dog.speak(); // Output: Buddy barks.

Sep 02, 2024
Read More
Tutorial
javascript

Asynchronous JavaScript: A Beginner's Guide

In synchronous programming, tasks are performed one after another. Each task must be completed before the next one begins. This can lead to issues like blocking, where a long-running task prevents other tasks from executing.

Synchronous Example:

Aug 30, 2024
Read More
Tutorial
javascript

Understanding the DOM in JavaScript: A Comprehensive Guide

Navigating Between Nodes:

  • parentNode: Accesses the parent node.
  • childNodes: Accesses all child nodes.
  • firstChild / lastChild: Accesses the first or last child.
  • nextSibling / previousSibling: Accesses the next or previous sibling.

Aug 30, 2024
Read More
Tutorial
python

Enhancing Productivity with Custom Keyboard Shortcuts in Your IDE

Introduction

Keyboard shortcuts are an essential tool for developers, allowing them to perform tasks more quickly and efficiently without interrupting their flow. While most Integrated Development Environments (IDEs) come with a set of default shortcuts, customizing these shortcuts to fit your workflow can significantly enhance your productivity. In this tutorial, we’ll explore how to create custom keyboard shortcuts in popular IDEs like Visual Studio Code, JetBrains IDEs (such as IntelliJ IDEA and PyCharm), and Sublime Text. We’ll also discuss some best practices for choosing and managing shortcuts.

Aug 20, 2024
Read More
Tutorial
bash

Securing Your Linux Server: Best Practices and Tools

  • Update System Packages:

On Debian/Ubuntu-based systems:

Aug 19, 2024
Read More
Code
php

Generate the Fibonacci series

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!