JavaScript Program to Check Voting Eligibility
Use a simple JavaScript program like
if (age >= 18) { console.log('Eligible to vote'); } else { console.log('Not eligible to vote'); } to check if a person is old enough to vote.Examples
Input17
OutputNot eligible to vote
Input18
OutputEligible to vote
Input25
OutputEligible to vote
How to Think About It
To check voting eligibility, first get the person's age. Then compare the age with the minimum voting age, which is 18. If the age is 18 or more, the person can vote; otherwise, they cannot.
Algorithm
1
Get the person's age as input.2
Check if the age is greater than or equal to 18.3
If yes, print 'Eligible to vote'.4
If no, print 'Not eligible to vote'.Code
javascript
const age = 20; if (age >= 18) { console.log('Eligible to vote'); } else { console.log('Not eligible to vote'); }
Output
Eligible to vote
Dry Run
Let's trace the program with age = 20 through the code
1
Set age
age = 20
2
Check age >= 18
20 >= 18 is true
3
Print result
Print 'Eligible to vote'
| age | age >= 18 | output |
|---|---|---|
| 20 | true | Eligible to vote |
Why This Works
Step 1: Compare age with 18
The code uses age >= 18 to check if the person is old enough to vote.
Step 2: Print eligibility
If the condition is true, it prints 'Eligible to vote', otherwise 'Not eligible to vote'.
Alternative Approaches
Using a function
javascript
function checkVotingEligibility(age) { return age >= 18 ? 'Eligible to vote' : 'Not eligible to vote'; } console.log(checkVotingEligibility(16));
This approach makes the code reusable for different ages.
Using prompt for input
javascript
const age = parseInt(prompt('Enter your age:'), 10); if (age >= 18) { console.log('Eligible to vote'); } else { console.log('Not eligible to vote'); }
This allows user input in a browser environment.
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a single comparison operation, so it runs in constant time.
Space Complexity
It uses a fixed amount of memory for the age variable and output, so constant space.
Which Approach is Fastest?
All approaches run in constant time and space; using a function adds reusability but no performance cost.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple if-else | O(1) | O(1) | Quick checks |
| Function with ternary | O(1) | O(1) | Reusable code |
| Prompt input | O(1) | O(1) | Interactive user input |
Always check that the age input is a number before comparing.
Forgetting to use >= instead of >, which excludes age 18 from eligibility.