Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the height based on width and screen size ratio (width:height) in JavaScript
We are required to write a JavaScript function that takes in the width of the screen as the first argument and the aspect ratio (w:h) as the second argument. Based on these two inputs our function should return the height of the screen.
Understanding Aspect Ratios
An aspect ratio defines the proportional relationship between width and height. Common ratios include 16:9 (widescreen), 4:3 (traditional), and 21:9 (ultrawide). The formula is: height = (width × ratio_height) / ratio_width.
Example
Following is the code ?
const ratio = '18:11';
const width = 2417;
const findHeight = (ratio = '', width = 1) => {
const [w, h] = ratio
.split(':')
.map(Number);
const height = (width * h) / w;
return Math.round(height);
};
console.log(findHeight(ratio, width));
Output
Following is the console output ?
1477
How It Works
The function splits the ratio string by ':' to extract width and height values, converts them to numbers using map(Number), then applies the proportion formula. Math.round() ensures we get a whole pixel value.
Multiple Examples
const findHeight = (ratio = '', width = 1) => {
const [w, h] = ratio
.split(':')
.map(Number);
const height = (width * h) / w;
return Math.round(height);
};
// Common screen ratios
console.log('16:9 ratio, width 1920:', findHeight('16:9', 1920));
console.log('4:3 ratio, width 1024:', findHeight('4:3', 1024));
console.log('21:9 ratio, width 2560:', findHeight('21:9', 2560));
16:9 ratio, width 1920: 1080 4:3 ratio, width 1024: 768 21:9 ratio, width 2560: 1097
Enhanced Version with Validation
const findHeightSafe = (ratio, width) => {
if (!ratio || !ratio.includes(':')) {
throw new Error('Invalid ratio format. Use "width:height" format.');
}
const [w, h] = ratio.split(':').map(Number);
if (isNaN(w) || isNaN(h) || w <= 0 || h <= 0) {
throw new Error('Ratio values must be positive numbers.');
}
if (width <= 0) {
throw new Error('Width must be a positive number.');
}
return Math.round((width * h) / w);
};
try {
console.log(findHeightSafe('16:9', 1280));
console.log(findHeightSafe('invalid', 1280));
} catch (error) {
console.log('Error:', error.message);
}
720 Error: Invalid ratio format. Use "width:height" format.
Conclusion
This function efficiently calculates screen height from width and aspect ratio using simple proportion mathematics. Adding validation makes it production-ready for handling invalid inputs gracefully.
