JsGuide

Learn JavaScript with practical tutorials and code examples

tutorialbeginner8 min read

JavaScript Basics - Variables, Functions, and Control Flow

Learn the fundamentals of JavaScript programming including variables, functions, conditionals, and loops. Perfect for beginners starting their JavaScript journey.

By JSGuide Team

JavaScript Basics: Variables, Functions, and Control Flow

JavaScript is the programming language that powers the web. Whether you're building interactive websites, web applications, or even server-side applications, understanding JavaScript fundamentals is essential.

Variables and Data Types #

Declaring Variables #

JavaScript offers three ways to declare variables:

// const - for constants (cannot be reassigned)
const name = "Alice";
const age = 25;

// let - for variables that can change (block-scoped)
let score = 100;
let isActive = true;

// var - older way (function-scoped, avoid in modern JS)
var oldStyle = "avoid this";

Data Types #

JavaScript has several built-in data types:

// Numbers
const integer = 42;
const decimal = 3.14;
const negative = -10;

// Strings
const singleQuotes = 'Hello World';
const doubleQuotes = "Hello World";
const templateLiteral = `Hello ${name}`;

// Booleans
const isTrue = true;
const isFalse = false;

// Arrays
const fruits = ["apple", "banana", "orange"];
const numbers = [1, 2, 3, 4, 5];

// Objects
const person = {
    name: "John",
    age: 30,
    city: "New York"
};

Functions #

Functions are reusable blocks of code that perform specific tasks.

Function Declaration #

function greet(name) {
    return `Hello, ${name}!`;
}

const message = greet("World");
console.log(message); // Output: Hello, World!

Arrow Functions (ES6+) #

// Arrow function syntax
const greet = (name) => {
    return `Hello, ${name}!`;
};

// Shorter syntax for single expressions
const greetShort = name => `Hello, ${name}!`;

// Multiple parameters
const add = (a, b) => a + b;

console.log(add(5, 3)); // Output: 8

Control Flow #

Conditional Statements #

const age = 18;

// if-else statement
if (age >= 18) {
    console.log("You are an adult");
} else {
    console.log("You are a minor");
}

// Multiple conditions
const score = 85;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else if (score >= 70) {
    console.log("Grade: C");
} else {
    console.log("Grade: F");
}

Switch Statements #

const day = "Monday";

switch (day) {
    case "Monday":
        console.log("Start of the work week");
        break;
    case "Friday":
        console.log("TGIF!");
        break;
    case "Saturday":
    case "Sunday":
        console.log("Weekend!");
        break;
    default:
        console.log("Regular day");
}

Loops #

For Loops #

// Traditional for loop
for (let i = 0; i < 5; i++) {
    console.log(`Count: ${i}`);
}

// For...of loop (for arrays)
const fruits = ["apple", "banana", "orange"];

for (const fruit of fruits) {
    console.log(fruit);
}

// For...in loop (for object properties)
const person = { name: "John", age: 30, city: "NYC" };

for (const key in person) {
    console.log(`${key}: ${person[key]}`);
}

While Loops #

let count = 0;

while (count < 3) {
    console.log(`Count: ${count}`);
    count++;
}

// Do-while loop (executes at least once)
let number = 0;

do {
    console.log(`Number: ${number}`);
    number++;
} while (number < 3);

Array Methods #

JavaScript arrays come with many useful methods:

const numbers = [1, 2, 3, 4, 5];

// forEach - execute function for each element
numbers.forEach(num => console.log(num * 2));

// map - create new array with transformed elements
const doubled = numbers.map(num => num * 2);

// filter - create new array with elements that pass test
const evenNumbers = numbers.filter(num => num % 2 === 0);

// reduce - reduce array to single value
const sum = numbers.reduce((total, num) => total + num, 0);

// find - find first element that passes test
const firstEven = numbers.find(num => num % 2 === 0);

// findIndex - find index of first element that passes test
const firstEvenIndex = numbers.findIndex(num => num % 2 === 0);

// includes - check if array contains element
const hasThree = numbers.includes(3);

// sort - sort array elements
const sorted = [...numbers].sort((a, b) => b - a); // descending

console.log("Original:", numbers);
console.log("Doubled:", doubled);
console.log("Even numbers:", evenNumbers);
console.log("Sum:", sum);
console.log("First even:", firstEven);
console.log("First even index:", firstEvenIndex);
console.log("Has three:", hasThree);
console.log("Sorted desc:", sorted);

Objects and Properties #

Objects are collections of key-value pairs and are fundamental to JavaScript:

const person = {
    name: "Alice",
    age: 30,
    isEmployed: true,
    hobbies: ["reading", "coding", "hiking"]
};

// Accessing properties
console.log(person.name); // Dot notation
console.log(person["age"]); // Bracket notation

// Adding properties
person.email = "[email protected]";
person["phone"] = "123-456-7890";

// Modifying properties
person.age = 31;

// Deleting properties
delete person.isEmployed;

// Object methods
const calculator = {
    x: 10,
    y: 5,
    add: function() {
        return this.x + this.y;
    },
    multiply: () => this.x * this.y, // Arrow function - 'this' doesn't work
    subtract() { // ES6 shorthand
        return this.x - this.y;
    }
};

console.log(calculator.add()); // 15
console.log(calculator.subtract()); // 5

String Methods #

JavaScript strings have many useful methods:

const text = "  Hello World  ";

// Length and case
console.log(text.length); // 15
console.log(text.toUpperCase()); // "  HELLO WORLD  "
console.log(text.toLowerCase()); // "  hello world  "

// Trimming whitespace
console.log(text.trim()); // "Hello World"
console.log(text.trimStart()); // "Hello World  "
console.log(text.trimEnd()); // "  Hello World"

// Searching
console.log(text.includes("World")); // true
console.log(text.indexOf("World")); // 8
console.log(text.startsWith("  Hello")); // true
console.log(text.endsWith("World  ")); // true

// Extracting parts
console.log(text.slice(2, 7)); // "Hello"
console.log(text.substring(2, 7)); // "Hello"
console.log(text.substr(2, 5)); // "Hello" (deprecated)

// Replacing
console.log(text.replace("World", "JavaScript")); // "  Hello JavaScript  "
console.log(text.replaceAll("l", "L")); // "  HeLLo WorLd  "

// Splitting
const words = "apple,banana,orange".split(",");
console.log(words); // ["apple", "banana", "orange"]

// Template literals
const name = "Alice";
const age = 30;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message);

Number Methods and Math Object #

Working with numbers in JavaScript:

const num = 42.6789;

// Number methods
console.log(num.toFixed(2)); // "42.68"
console.log(num.toPrecision(4)); // "42.68"
console.log(parseInt("42.6789")); // 42
console.log(parseFloat("42.6789")); // 42.6789

// Math object
console.log(Math.round(num)); // 43
console.log(Math.floor(num)); // 42
console.log(Math.ceil(num)); // 43
console.log(Math.max(1, 5, 3)); // 5
console.log(Math.min(1, 5, 3)); // 1
console.log(Math.random()); // Random number between 0-1
console.log(Math.abs(-42)); // 42
console.log(Math.sqrt(16)); // 4
console.log(Math.pow(2, 3)); // 8

// Generate random integer between min and max
function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(randomInt(1, 10)); // Random number between 1-10

Type Checking and Conversion #

Understanding types and converting between them:

// Type checking
console.log(typeof "hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (this is a known quirk)
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function() {}); // "function"

// Better array checking
console.log(Array.isArray([])); // true
console.log(Array.isArray({})); // false

// Type conversion
console.log(Number("42")); // 42
console.log(String(42)); // "42"
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean("hello")); // true

// Implicit conversion (coercion)
console.log("5" + 3); // "53" (string concatenation)
console.log("5" - 3); // 2 (numeric subtraction)
console.log("5" * 3); // 15 (numeric multiplication)
console.log(true + 1); // 2 (true becomes 1)
console.log(false + 1); // 1 (false becomes 0)

Best Practices #

  1. Use const by default, let when you need to reassign
  2. Use arrow functions for shorter, cleaner code
  3. Use template literals for string interpolation
  4. Use descriptive variable names
  5. Keep functions small and focused
  6. Use strict equality (===) instead of loose equality (==)
  7. Initialize variables to avoid undefined errors
  8. Use proper indentation and consistent code style
  9. Comment your code when logic is complex
  10. Handle edge cases and validate inputs

Common Mistakes to Avoid #

  1. Using var instead of let or const
  2. Forgetting break in switch statements
  3. Modifying arrays/objects declared with const
  4. Not understanding scope differences

Next Steps #

Now that you understand the basics, you can explore:

Summary #

JavaScript basics include:

  • Variables (const, let) and data types
  • Functions (traditional and arrow functions)
  • Control flow (if/else, switch, loops)
  • Array methods for data manipulation

Practice these concepts regularly, and you'll build a strong foundation for advanced JavaScript development!

Related Tutorials

Tutorialintermediate

Asynchronous JavaScript - Promises, Async/Await, and Fetch

Master asynchronous programming in JavaScript with promises, async/await, and the Fetch API. Learn to handle API calls, timers, and concurrent operations.

#javascript #async #promises +2 more
Read Tutorial →
TutorialBeginner
4 min min read

Best Way to Learn JavaScript: Common Questions Answered

Find answers to frequently asked questions about the best way to learn JavaScript, including timelines, resources, and effective study methods.

#javascript #learning #faq +2 more
Read Tutorial →

Last updated: Jan 11, 2025

Tutorialintermediate

DOM Manipulation with JavaScript - Complete Guide

Master DOM manipulation in JavaScript. Learn to select elements, modify content, handle events, and create dynamic web pages with practical examples.

#javascript #dom #manipulation +2 more
Read Tutorial →
Tutorialintermediate

ES6+ Features Every JavaScript Developer Should Know

Master modern JavaScript with ES6+ features including arrow functions, destructuring, modules, async/await, and more essential syntax improvements.

#javascript #es6 #modern +2 more
Read Tutorial →