JavaScript Basics: Variables, Data Types, and Operators


JavaScript variables, data types, and operators are foundational to writing code and creating dynamic web applications. This tutorial will guide you through these essentials, explaining how to store and manipulate values in JavaScript.



1. Declaring Variables


JavaScript has three main keywords to declare variables: `var`, `let`, and `const`.

  • let: Used to declare variables that can change later.
  • const: Declares variables with values that should not change.
  • var: Older keyword, now less commonly used in modern JavaScript.


Example:

JavaScript Code
  1. let name = "Alice"; // a variable that can be changed
  2. const birthYear = 1990; // a constant that cannot be changed




2. Data Types in JavaScript


JavaScript supports various data types, including:

String: Text data, defined using single (`'`) or double (`"`) quotes.
JavaScript Code
  1. let greeting = "Hello, world!";


Number: Numerical data, including integers and decimals.
JavaScript Code
  1. let age = 25;


Boolean: Represents true or false values.
JavaScript Code
  1. let isStudent = true;


Undefined: A variable that has been declared but not assigned a value.
JavaScript Code
  1. let score; // undefined variable


Null: Represents an empty or unknown value.
JavaScript Code
  1. let emptyValue = null;




3. Operators in JavaScript


Operators allow you to perform actions on variables and values. Here are some common types:

Arithmetic Operators: Used for mathematical calculations.
JavaScript Code
  1. let x = 10;
  2. let y = 5;
  3. let sum = x + y; // addition
  4. let product = x * y; // multiplication


Assignment Operators: Used to assign values.
JavaScript Code
  1. let a = 10;
  2. a += 5; // a = a + 5


Comparison Operators: Compare two values and return true or false.
JavaScript Code
  1. let isEqual = (x == y); // checks if x equals y
  2. let isGreater = (x > y); // checks if x is greater than y


Logical Operators: Used to combine conditions.
JavaScript Code
  1. let isAdult = (age >= 18) && isStudent; // both conditions must be true




4. Working with Strings


Strings are sequences of characters used to represent text.


Concatenation: Combine two strings using `+`.
JavaScript Code
  1. let firstName = "Alice";
  2. let lastName = "Smith";
  3. let fullName = firstName + " " + lastName;


Template Literals: Use backticks and `${}` for embedded expressions.
JavaScript Code
  1. let age = 25;
  2. let message = `I am ${age} years old.`;




Conclusion


These basics of variables, data types, and operators provide a foundation for JavaScript programming. Understanding how to store, manipulate, and evaluate data will help you progress to more complex coding tasks!
AI's Avatar
Author:
Views:
156
Rating:
There are currently no comments for this tutorial, login or register to leave one.