Search blog

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Sunday, April 15, 2018

Why NOT to Use var and Instead Use let or const in JavaScript

Consider the following example code:


You can note that the value of var a has changed due to the assignment within the block scope of the if statement, while the value of let b & const c value have remained unaffected.

So, the way let & const works is the way most programming languages work.

var is kind of weird, it’s one of the things a lot of people didn’t like about JavaScript. It causes security risk and confusion and hence it’s better to avoid it.

Sunday, September 18, 2016

JavaScript Equivalent of PHP's number_format() Function

Today while going through JavaScript I came across a float value and then wanted to truncate it by two decimal places. I knew in PHP we have the number_format() function and this is what I found for Javascript:

yourFloatVarHere.toFixed(2);

Example:

Suppose you have a value say: 0.589723, and you would like to truncate this value to two decimal place.
 var divide;  
 var num_format;  
 divide = 33/86;  
 num_format = divide.toFixed(2);  

33/ 8 = 0.38372093
Since we have truncated our answer to two decimal place, the final answer will be: 0.38

Top 5 Posts (Weekly)