New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming JavaScript Functions and Conditionals

Functions and Conditionals

JavaScript

Write functions and use if/else to make decisions.

Lesson 2 of 4 Tutorial
0/4 completed

Functions and Conditionals

Functions

// Function declaration
function greet(name) {
    return "Hello, " + name + "!";
}

// Arrow function
const add = (a, b) => a + b;

console.log(greet("Alice"));  // "Hello, Alice!"
console.log(add(3, 5));       // 8

If/Else

let score = 75;

if (score >= 90) {
    console.log("Excellent!");
} else if (score >= 70) {
    console.log("Good job!");
} else if (score >= 50) {
    console.log("You passed.");
} else {
    console.log("Keep trying.");
}

Example

// Function to calculate grade
function getGrade(score) {
    if (score >= 90) return "A";
    if (score >= 80) return "B";
    if (score >= 70) return "C";
    if (score >= 60) return "D";
    return "F";
}

// Test it
let scores = [95, 82, 67, 55, 73];
for (let s of scores) {
    console.log("Score " + s + " = Grade " + getGrade(s));
}

// Function to check if number is even or odd
function evenOrOdd(n) {
    return n % 2 === 0 ? "even" : "odd";
}

console.log(evenOrOdd(7));   // "odd"
console.log(evenOrOdd(12));  // "even"

Exercises

Exercise 1. Write an isEven Function Medium
Write a function isEven(n) that returns true when n is even and false otherwise.
Use the modulo operator: return n % 2 === 0;
function isEven(n) {
    
}
Expected Output
isEven(4) === true, isEven(7) === false.

Lesson Nav

Lesson sections