Here are 20 JavaScript programs with solutions covering: ✔ if ✔ if-else ✔ if-else if ✔ nested if ✔ one-line (ternary) conditions
🔹 1. Positive number (if)
let num = 5;if (num > 0) { console.log("Positive"); }
🔹 2. Even or odd (if-else)
let num = 4;if (num % 2 === 0) { console.log("Even"); } else { console.log("Odd"); }
🔹 3. Voting eligibility (if-else)
let age = 16;if (age >= 18) { console.log("Eligible"); } else { console.log("Not eligible"); }
🔹 4. Largest of two numbers (if-else)
let a = 10, b = 20;if (a > b) { console.log("a is greater"); } else { console.log("b is greater"); }
🔹 5. Divisible by 3 (if)
let num = 9;if (num % 3 === 0) { console.log("Divisible by 3"); }
🔹 6. Grade system (if-else if)
let marks = 85;if (marks >= 90) { console.log("A"); } else if (marks >= 70) { console.log("B"); } else if (marks >= 50) { console.log("C"); } else { console.log("Fail"); }
🔹 7. Largest of three numbers (if-else if)
let a = 5, b = 8, c = 3;if (a > b && a > c) { console.log("a is largest"); } else if (b > c) { console.log("b is largest"); } else { console.log("c is largest"); }
🔹 8. Leap year (if-else)
let year = 2024;if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) { console.log("Leap year"); } else { console.log("Not leap year"); }
🔹 9. Check number range (if)
let num = 25;if (num >= 10 && num <= 50) { console.log("Within range"); }
let marks = 75;if (marks >= 90) { console.log("Grade A"); } else if (marks >= 70) { console.log("Grade B"); } else { console.log("Grade C"); }
✅ 4. Nested if
An if inside another if.
✅ Example:
let age = 20; let hasLicense = true;if (age >= 18) { if (hasLicense) { console.log("You can drive"); } else { console.log("Get a license first"); } }
✅ 5. Ternary Operator (Short if-else)
A short form of if...else.
📌 Syntax:
condition ? value1 : value2;
✅ Example:
let age = 16;let result = (age >= 18) ? "Adult" : "Minor"; console.log(result);
🔷 Important Concepts
🔹 Comparison Operators
Operator
Meaning
==
Equal (loose)
===
Equal (strict)
!=
Not equal
!==
Strict not equal
><>=<=
Comparison
👉 Always prefer === (strict equality)
🔹 Logical Operators
Operator
Meaning
&&
AND
!
NOT
✅ Example:
let age = 20; let hasID = true;if (age >= 18 && hasID) { console.log("Allowed entry"); }
🔷 Practice Programs (Very Important 🚀)
🟢 Beginner Level
1. Check Positive or Negative
let num = -5;if (num >= 0) { console.log("Positive"); } else { console.log("Negative"); }
2. Find Largest of Two Numbers
let a = 10, b = 20;if (a > b) { console.log("A is larger"); } else { console.log("B is larger"); }
3. Check Divisible by 5
let num = 25;if (num % 5 === 0) { console.log("Divisible by 5"); } else { console.log("Not divisible"); }
🟡 Intermediate Level
4. Find Largest of Three Numbers
let a = 10, b = 25, c = 15;if (a > b && a > c) { console.log("A is largest"); } else if (b > c) { console.log("B is largest"); } else { console.log("C is largest"); }
5. Check Leap Year
let year = 2024;if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) { console.log("Leap Year"); } else { console.log("Not a Leap Year"); }
6. Grade Calculator
let marks = 85;if (marks >= 90) { console.log("A"); } else if (marks >= 75) { console.log("B"); } else if (marks >= 50) { console.log("C"); } else { console.log("Fail"); }
Double-click on the exe file and initiate installation with exe , select all default options, and complete the installation.
Create a folder in C Drive with the name GithubCode, folder path should be C:\GithubCode
Open folder and right-click -> show more options -> click on open git bash here.
It will open the Git terminal in the C:\GithubCode folder.
Run a command to check the git option git –help
It will show available git commands
Steps to Add User Credentials in Git Config File
Open the Git terminal in the C:\GitHubCode folder
Run the command below to open the config file -> git config –global –edit -> It will open the config file in the vi editor
Press i to enable insert mode, it should show –insert– in the bottom.
Now use keyboard arrows and update the name and email with your git username and git email. [user] name = Divya4255 email = divya.smsrinivas1995@gmail.com
Make sure to remove # from the name and email line in the config file.
Press the ESCAPE key to disabled insert mode.
start type :wq and press enter -> It will save the configuration details.
Steps to Clone the Repository on the User’s Machine
Go to the GitHub server, log in with your credentials
Navigate to the repository that we have already created.
Click on the Code (green color) button, and copy the repository from there.
Open the Git terminal in the C:\GitHubCode folder.
Run the command below to clone the repo -> git clone https://github.com/Divya4255/AutomationPractice.git
Hit Enter -> It will clone repository from server to your local machine.
The repository folder will be created on the local machine.
Steps to Create a New File and Push to the GitHub Server
Create a text file in the git repository folder (AutomationPractice) and rename as demo_file.txt
Open the text file and add some content to the file -> save the file.
Open the Git terminal in C:\GitHubCode\AutomationPractice folder.
Run the git status command -> git status: it will show the new demo file in red color.
Run the git add command -> git add file_path/filename # It will add the file to GitHub tracking
Check the status again. -> git status # It will show the demo file in green color.
Initiate commit operation -> git commit -m “adding new file to repo.” -> It will complete the commit operation.
Initiate the git push operation. -> git push -> It will launch a pop-up -> Click and open in browser option. -> It will open in browser and click on the Authorize git ecosystem button. -> Now push will be successful and file will be push to the server. -> Check on GitHub server, the file is available on GitHub server.
Home Work For Practice:
Create three different file and push them to the server.
Update file1 and push(git status, git add, git commit, git push) it.
Rename file2 and push it from the terminal.
Delete file3 and push it from terminal.
Create a Common Repo and Provide Access
Create a repository with the name: e.g., GTM_PlaywrightTS_BATCH11
Get students’ email and provide Access to collaborate. Go to Repository -> Settings -> Collaborators -> Add People -> Enter Your email -> Select User -> Add to Repository
People will receive an invitation via email.
Open the email, click View Invitation, then accept the invitation.
Everyone has to accept the invitation.
Make sure to accept the invitation from the laptop, and your GitHub account is already open in the same browser where you open the mail account.
Once the invitation is accepted, the user will be able to see the common repository.
Clone the Common Repo, Add folder your name
Go to the common repository -> click on code (green button) -> click on copy clipboard to copy URL.
Open the Git terminal in the C:\GitHubCode folder on the local system
Run this command to clone the common repository -> git clone https://github.com/sqatools/GTM_PlaywrightTS_BATCH11.git
It will clone the command repository into a C:\GitHubCode to the local directory. -> repository folder name: GTM_PlaywrightTS_BATCH11
Create folder with your name in repo e.g. Deepesh and Add file inside the your folder e.g. first_file.txt
Navigate back to git terminal.
ON git terminal run below command to go inside repository folder. cd GTM_PlaywrightTS_BATCH11 -> It will open GTM_PlaywrightTS_BATCH11 folder.
Check status using below command -> git status : New Folder name will show in red color.
If push is rejected repeat this steps until push it not successful. -> git pull -> it will open merge editor -> we have to close the edit with command using :wq (save file) -> Once the edit is closed, re-initiate the push operation -> git push -> if push is still rejected (Repeat again from “git pull” command)
################ Multi branching in git
Go to Git Repository on server : GTM_PlaywrightTS_BATCH11
Click on repository dropdown. default is main
click on view all branches.
Create branch with your name e.g. deepesh_branch. -> New Branch -> Provide Branch Name e.g. firstname_branch -> click on create branch button -> Verify branch is created successfully.
Open git terminal in repository folder
run command to update the repo -> git pull (all newly created branches will show in the console output)
Check current active branch -> git branch : It will show main as active branch in green color.
Switch to new branch. -> git checkout deepesh_branch
check again active branch -> git branch : your branch will show as active branch in green color e.g. deepesh_branch
Go to your dedicated folder and add file inside the folder Folder Name : Deepesh Filename : deepesh_feature_file.txt (don’t add space in filename)
11 Go back to terminal and check status -> git status : newly added file will show in red color
Run git add command -> git add
Initiate commit operation -> git commit -m “added new file to feature branch”
Initiate push operation -> git push : file will push to the server on dedicated branch.
Go to GitHub server and verify file is available in dedicated folder in your branch.
################### Create pull from server
Go to server and navigate to repository.
Click on “Compare & pull request” button (green button)
Provide pull request description.
Add reviwers to review the code.
Click on create pull button.
################### Create workflow file in branch
Go to repository on GitHub server
Navigate to Actions Tab.
Click on New Workflow (green color) button
Select any workflow from given list. e.g. simple workflow
click on configure button
Select your branch from left side dropdown e.g. deepesh_branch.
Provide workflow name default name is blank.yml default path: GTM_Playwright_Batch11/.gitHub/workflow/blank.yml keep this path alive pull_request: branches: [ “main” ] remove this part: this will execute workflow for every single push push: branches: [ “main” ]
click on commit changes button.
It will open pop to provide commit message -> we can click on commit changes and push to the current branch.
It will create workflow on your dedicated branch and execute along with each PR.
########## Resolve Merge conflict
conflict scenario
Create file1 in main branch add some code from line 1 to 10.
Create new branch from main branch and then modify same file1 and same line numbers from 1 to 10.
In main branch, modify same on same number of lines and push it.
Create pull request from feature to main branch
It will create conflict.
We have to resolve conflict and merge the change
Steps to reproduce conflict scenario
Open git terminal in repository folder. -> make sure your current active branch should be main -> if not then you can switch to main branch. -> ‘git checkout main’ # it will switch to main branch. -> ‘git pull’ : Update your main branch with all change from server. -> ‘git branch’ : current active branch should be main branch in green color
Create a file with name e.g. dy_conflict_file.txt, and code snipet in the file, and save the file. var num1 = 10 if (num1%2 == 0) { console.log(“This is even number”) } else { console.log(“This is odd number”) }
Push file to main branch. -> git status: show file in read color -> git add -> git status : show file in green color -> git commit -m “added file” -> git push : It push is rejected, then pull the code and perform push operation. -> git pull : it will open editor, we have close it with :wq! command. -> then try to push again, repeat (pull, push), until it is not successful.
Create a branch from local git bash terminal. -> git checkout -b “dy_conflict_branch”
Update dy_conflict_file.txt file as given below. if (num1%2 == 0) { console.log(“This is even number, divisible by 2”) } else { console.log(“This is odd number, not divisible by 2”) }
go back to terminal and run below command -> git status : shows in red color -> git add -> git status : shows file in green color -> git commit -m “initiate commit operation”
run below command to push local branch to server -> git push –set-upstream origin dy_conflict_branch -> push will be successful in feature.
change branch from conflict branch to main branch in terminal -> git checkout main -> git pull : it will update all changes from server to local machine.
Open conflict file in your folder and update few change in file content. var num1 = 10 if (num1%2 == 0) { console.log(“condition is True”) console.log(“This is even number, can divide by 2”) } else { console.log(“condition is False”) console.log(“This is odd number, can not divide by 2”) }
push the file change in main branch. -> git status -> git add -> git commit -m “updated file” -> git push (repeat pull and push commands)
Go to GitHub server and create pull request from conflict branch to main branch -> go to repository -> search your branch name and select the branch. -> if the branch is old, then it will show contribute button -> click on contribute button and click on ‘Open pull request’ button. -> Provide request details (reviewer, description assignee) -> click on create pull request button.
It will show merge conflict between main branch and feature branch. -> ‘merge pull request’ button will be in disable state. This branch has conflicts that must be resolved Use the web editor or the command line to resolve conflicts before continuing. Deepesh/dy_conflict_file.txt
—— Resolve merge conflict locally ——
Go back to git terminal
switch to feature branch. -> git checkout dy_conflict_branch
run a command on terminal to update feature branch with main branch -> git pull origin main -> it will show conflict message on terminal Auto-merging Deepesh/dy_conflict_file.txt CONFLICT (content): Merge conflict in Deepesh/dy_conflict_file.txt Automatic merge failed; fix conflicts and then commit the result.
Open dy_conflict_file.txt on local machine, will show below content
var num1 = 10 if (num1%2 == 0) {
HEAD : change from feature BRANCH (dy_conflict_branch)
<<<<<<< HEAD console.log(“This is even number, divisible by 2”) } else {
console.log(“This is odd number, not divisible by 2”)
Changes from MAIN branch
console.log(“condition is True”) console.log(“This is even number, can divide by 2”) } else { console.log(“condition is False”) console.log(“This is odd number, can not divide by 2”)
9f9d33c6d4f9d945d512c3b40e36783b758295fd }
Update the file content as per your requirements. var num1 = 10 if (num1%2 == 0) { console.log(“condition is True”) console.log(“This is even number, divisible by 2”) } else { console.log(“condition is False”) console.log(“This is odd number, not divisible by 2”) }
go to git terminal and run below commands -> git status : It will show in red color -> git add -> git commit -m “resolved merge” -> git push
Once the push is successful, merge will conflict will be resolved in pull request -> Now go back to git server and check pull request, there is no conflict anymore.
Operators in JavaScript are symbols used to perform operations on variables and values. They are essential for writing logic, calculations, and conditions
1. Arithmetic Operators
Used for mathematical calculations.
Operator
Description
Example
+
Addition
5 + 2 = 7
-
Subtraction
5 - 2 = 3
*
Multiplication
5 * 2 = 10
/
Division
10 / 2 = 5
%
Modulus (remainder)
5 % 2 = 1
**
Exponentiation
2 ** 3 = 8
Example:
let a = 10; let b = 3;console.log(a + b); // 13 console.log(a % b); // 1
In JavaScript, variables are declared using var, let, and const. These keywords define how variables behave in terms of scope and mutability. Modern JavaScript development strongly favors let and const because they provide better control and reduce unexpected bugs. If you’re building dynamic websites or applications, understanding variables is absolutely essential because they drive logic, interactivity, and data handling.
Why Variables Matter in Programming
Variables allow your program to process user input, perform calculations, and manage application state. Think of them as the memory of your application. Without variables, even simple tasks like storing a username or calculating a total price would be impossible.
Real-Life Analogy for Variables
Consider a backpack you carry every day. You can put books, gadgets, or food inside it. Some items you replace frequently, while others stay the same. That’s exactly how variables behave depending on how you declare them.
Types of Variable Declarations
Understanding var
The var The keyword is the oldest method for declaring variables in JavaScript. It is function-scoped, meaning it is accessible throughout the function in which it is defined. One unique characteristic of var is that it allows both redeclaration and reassignment, which can sometimes introduce bugs if not handled carefully.
var name = "John"; var name = "Doe"; // Allowed console.log(name); // Output: Doe
Because of these limitations, developers rarely use var in modern applications unless maintaining legacy code.
Understanding let
The let keyword was introduced in ES6 and is now widely used. It provides block-level scope, meaning the variable is only accessible within the block {} where it is defined. This makes code more predictable and easier to debug.
let age = 25; age = 30; // Allowed // let age = 35; ❌ Not allowed
Using let ensures that variables don’t accidentally leak outside their intended scope.
Understanding const
The const keyword is used to declare variables whose values should not change. Once assigned, a const variable cannot be reassigned. However, if the variable holds an object or array, its internal properties can still be modified.
const country = "India"; // country = "USA"; ❌ Error
This makes const ideal for values that should remain constant throughout the program.
Key Differences Between var, let, and const
Scope Explained
Keyword
Scope Type
var
Function/Global
let
Block
const
Block
Reassignment vs Redeclaration
Keyword
Reassign
Redeclare
var
Yes
Yes
let
Yes
No
const
No
No
Hoisting Behavior
JavaScript uses a mechanism called hoisting, where variable declarations are moved to the top of their scope during execution. However, var is initialized with undefined, while let and const remain uninitialized until execution reaches their declaration.
Rules for Naming Variables
Valid Naming Conventions
Start with a letter, _, or $
Can include numbers (not at the beginning)
Case-sensitive
Common Mistakes to Avoid
Using reserved keywords
Starting names with numbers
Using unclear variable names
Rules to define a variable name
✅ 1. Allowed Characters
Variable names can contain:
Letters (a–z, A–Z)
Digits (0–9)
Underscore (_)
Dollar sign ($)
✔ Example:
let name; let user1; let _count; let $price;
❌ 2. Cannot Start with a Number
A variable name must NOT start with a digit
❌ Wrong:
let 1name;
✔ Correct:
let name1;
❌ 3. No Spaces Allowed
Variable names cannot contain spaces
❌ Wrong:
let user name;
✔ Correct:
let userName;
❌ 4. Cannot Use Reserved Keywords
You cannot use JavaScript reserved words like:
let, var, const, if, else, function, etc.
❌ Wrong:
let var = 10;
✅ 5. Case Sensitive
JavaScript is case-sensitive
let name = "John"; let Name = "Doe"; // different variable