Are parentheses ignored when assigning JSX to a variable - javascript

I'm learning about the javascript basics. The two lines of code seem equivalent and I'm wondering if the parser simply ignores the parentheses in the second case:
var a = 5 + 5;
var b = (5 + 5);
EDIT:
I realize the context of the question might of help after going through the comments, which are helpful. I was trying to assign some JSX to a variable and noticed that the parentheses seem optional:
var a =
<div>
<SomeComponent />
</div>;
var b = (
<div>
<SomeComponent />
</div>
);
In the case of a return statement, I understand that parentheses are needed due to automatic semicolon injection. But in case of a simple assignment do the parentheses still matter?
EDIT 2:
Thanks for the comments and answer that help me narrow down and articulate my question. I think what I really meant to ask is, does JSX parser (e.g. Babel) ignore the parentheses in such a case? Since both will be transpiled into:
var a = React.createElement(
"div",
null,
React.createElement(
SomeComponent,
null
)
)

They're not ignored, but simple mathematics tells you that:
5 + 5 == (5 + 5)
If you had a different set of values, it would change - e.g.:
var a = (5 * 5) + 5 * 5;
var b = 5 * (5 + 5) * 5;
var c = 5 * 5 + (5 * 5);
var d = (5 * 5 + 5) * 5;
var e = 5 * (5 + 5 * 5);
var f = (5 * 5 + 5 * 5);
console.log(a); // 50
console.log(b); // 250
console.log(c); // 50
console.log(d); // 150
console.log(e); // 150
console.log(f); // 50
It depends on the Order of Operations (aka BODMAS/BIDMAS/BEDMAS etc.)

Related

JavaScript difference between ' ' and (' ')

What is the difference between '' and ('')
let n = 'a' + 1
let n = ('a') + 1
let n = ('a') + (1)
what is the difference?
They are same both.
() is important for precedence especially if there is math operations and concat with string together. Read this info
var example1='x' + (1+2); console.log(example1);
var example2='x'+1+2; console.log(example2);
var example3=("x"+4)/2; console.log(example3);
var example4=("x")+(4/2); console.log(example4);
Taking a property from an object works without parentheses.
var value = { x: 1 }.x;
console.log(value);
Basically the only need for parenthesis is to destructure the item ouside of a declaration.
Does not work
var foo;
{ foo } = { foo: 1 }; // assigment to a block statement
console.log(foo);
Works
var foo;
({ foo } = { foo: 1 });
console.log(foo);
Another use case for parentheses, is by takeing an arrow function which returns an object.
var fn = foo => ({ foo });
console.log(fn(1));
There’s no difference between '' and (''). Parentheses make no difference in your code examples.
Parentheses (), known as the Grouping Operator, are used to change the order of evaluation of an expression. Consider the following expression:
1 + 2 * 3
As the * operator has higher precedence, first 2 * 3 will be evaluated and then the result of multiplication will be added to 1.
const result = 1 + 2 * 3;
console.log(result);
If you want to do addition first, then you can use ().
(1 + 2) * 3
Adding parentheses will change how the expression is evaluated. Instead of multiplication, now 1 + 2 will be evaluated first and then the result of addition will be multiplied with 3.
const result = (1 + 2) * 3;
console.log(result);
Grouping Operator ()
Grouping operator implies the precedence of evaluation of an expression or subexpression.
With the grouping operator, it is possible to override the normal precedence of evaluation by telling the compiler an expression with lower precedence should be evaluated before an expression with higher priority.
console.log(3 + 4 * 5); // 3 + 20
// expected output: 23
console.log(4 * 3 ** 2); // 4 * 9
// expected output: 36
let a;
let b;
console.log(a = b = 5);
// expected output: 5
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Javascript countdown - always 2 numbers [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 3 years ago.
In JavaScript, I need to have padding.
For example, if I have the number 9, it will be "0009". If I have a number of say 10, it will be "0010". Notice how it will always contain four digits.
One way to do this would be to subtract the number minus 4 to get the number of 0s I need to put.
Is there was a slicker way of doing this?
ES2017 Update
You can use the built-in String.prototype.padStart()
n = 9;
String(n).padStart(4, '0'); // '0009'
n = 10;
String(n).padStart(4, '0'); // '0010'
Not a lot of "slick" going on so far:
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
When you initialize an array with a number, it creates an array with the length set to that value so that the array appears to contain that many undefined elements. Though some Array instance methods skip array elements without values, .join() doesn't, or at least not completely; it treats them as if their value is the empty string. Thus you get a copy of the zero character (or whatever "z" is) between each of the array elements; that's why there's a + 1 in there.
Example usage:
pad(10, 4); // 0010
pad(9, 4); // 0009
pad(123, 4); // 0123
pad(10, 4, '-'); // --10
function padToFour(number) {
if (number<=9999) { number = ("000"+number).slice(-4); }
return number;
}
Something like that?
Bonus incomprehensible-but-slicker single-line ES6 version:
let padToFour = number => number <= 9999 ? `000${number}`.slice(-4) : number;
ES6isms:
let is a block-scoped variable (as opposed to var’s functional scoping)
=> is an arrow function that, among other things, replaces function and is prepended by its parameters
If an arrow function takes a single parameter, you can omit the parentheses (hence number =>)
If an arrow function body has a single line that starts with return, you can omit the braces and the return keyword and simply use the expression
To get the function body down to a single line, I cheated and used a ternary expression
Try:
String.prototype.lpad = function(padString, length) {
var str = this;
while (str.length < length)
str = padString + str;
return str;
}
Now test:
var str = "5";
alert(str.lpad("0", 4)); //result "0005"
var str = "10"; // note this is string type
alert(str.lpad("0", 4)); //result "0010"
DEMO
In ECMAScript 2017 , we have new method padStart and padEnd which has below syntax.
"string".padStart(targetLength [,padString]):
So now we can use
const str = "5";
str.padStart(4, "0"); // "0005"
Funny, I recently had to do this.
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
Use like:
padDigits(9, 4); // "0009"
padDigits(10, 4); // "0010"
padDigits(15000, 4); // "15000"
Not beautiful, but effective.
You did say you had a number-
String.prototype.padZero= function(len, c){
var s= '', c= c || '0', len= (len || 2)-this.length;
while(s.length<len) s+= c;
return s+this;
}
Number.prototype.padZero= function(len, c){
return String(this).padZero(len,c);
}
You could do something like this:
function pad ( num, size ) {
return ( Math.pow( 10, size ) + ~~num ).toString().substring( 1 );
}
Edit: This was just a basic idea for a function, but to add support for larger numbers (as well as invalid input), this would probably be better:
function pad ( num, size ) {
if (num.toString().length >= size) return num;
return ( Math.pow( 10, size ) + Math.floor(num) ).toString().substring( 1 );
}
This does 2 things:
If the number is larger than the specified size, it will simply return the number.
Using Math.floor(num) in place of ~~num will support larger numbers.
This is not really 'slick' but it's faster to do integer operations than to do string concatenations for each padding 0.
function ZeroPadNumber ( nValue )
{
if ( nValue < 10 )
{
return ( '000' + nValue.toString () );
}
else if ( nValue < 100 )
{
return ( '00' + nValue.toString () );
}
else if ( nValue < 1000 )
{
return ( '0' + nValue.toString () );
}
else
{
return ( nValue );
}
}
This function is also hardcoded to your particular need (4 digit padding), so it's not generic.
For fun, instead of using a loop to create the extra zeros:
function zeroPad(n,length){
var s=n+"",needed=length-s.length;
if (needed>0) s=(Math.pow(10,needed)+"").slice(1)+s;
return s;
}
Since you mentioned it's always going to have a length of 4, I won't be doing any error checking to make this slick. ;)
function pad(input) {
var BASE = "0000";
return input ? BASE.substr(0, 4 - Math.ceil(input / 10)) + input : BASE;
}
Idea: Simply replace '0000' with number provided... Issue with that is, if input is 0, I need to hard-code it to return '0000'. LOL.
This should be slick enough.
JSFiddler: http://jsfiddle.net/Up5Cr/

Why isn't this code working to find the sum of multiples of 3 and 5 below the given number?

I've started with some problems on HackerRank, and am stuck with one of the Project Euler problems available there.
The problem statement says: Find the sum of all the multiples of 3 or 5 below N
I've calculated the sum by finding sum of multiple of 3 + sum of multiples of 5 - sum of multiples of 15 below the number n
function something(n) {
n = n-1;
let a = Math.trunc(n / 3);
let b = Math.trunc(n / 5);
let c = Math.trunc(n / 15);
return (3 * a * (a + 1) + 5 * b * (b + 1) - 15 * c * (c + 1)) / 2;
}
console.log(something(1000)); //change 1000 to any number
With the values of num I've tried, it seems to work perfectly, but with two out of five test cases there, it returns a wrong answer (I can't access the test cases).
My question is what is the problem with my code? as the logic seems to be correct to me at least.
Edit: Link to problem page
Some of the numbers in the input are probably larger than what javascript can handle by default. As stated in the discussion on the hackkerrank-site, you will need an extra library (like: bignumber.js) for that.
The following info and code was posted by a user named john_manuel_men1 on the discussion, where several other people had the same or similar problems like yours
This is how I figured it out in javascript. BigNumber.js seems to store the results as strings. Using the .toNumber() method shifted the result for some reason, so I used .toString() instead.
function main() {
var BigNumber = require('bignumber.js');
var t = new BigNumber(readLine()).toNumber();
var n;
for(var a0 = 0; a0 < t; a0++){
n = new BigNumber(readLine());
answer();
}
function answer() {
const a = n.minus(1).dividedBy(3).floor();
const b = n.minus(1).dividedBy(5).floor();
const c = n.minus(1).dividedBy(15).floor();
const sumThree = a.times(3).times(a.plus(1)).dividedBy(2);
const sumFive = b.times(5).times(b.plus(1)).dividedBy(2);
const sumFifteen = c.times(15).times(c.plus(1)).dividedBy(2);
const sumOfAll = sumThree.plus(sumFive).minus(sumFifteen);
console.log(sumOfAll.toString());
}
}

Computing the volume of a regular tetrahedron with edge length

Im trying to figure out how to write a JavaScript program that computes and outputs the volume of a regular tetrahedron. This is how far I got but it seems to get a error and not compute the right numbers after.
The equation for the triangle is
v = a3
6 √ 2
Sorry about the code i dont know how to post things on here very effectively. So this is my variables
var a = parseFloat(document.getElementById('length').value);
var b = (a * a * a) / 6 * Math.sqrt(2)
You are very close. You are missing some parenthesis around 6 * Math.sqrt(2)
Your code is doing (a*a*a) / 6 and then multiplying that result by the square root of 2.
You can read up on Operator Precedence
var a = 4;
var b = (a * a * a) / (6 * Math.sqrt(2))
console.log(b);
You can also use Math.pow()
var a = 4;
var b = Math.pow(a,3) / (6 * Math.sqrt(2))
console.log(b);

What does the i--> opeator do in JavaScript?

So I took a look at the code that controls the counter on the SO advertising page. Then I saw the line where this occured i-->. What does this do?
Here is the full code:
$(function(){
var visitors = 5373891;
var updateVisitors = function()
{
visitors++;
var vs = visitors.toString(),
i = Math.floor(vs.length / 3),
l = vs.length % 3;
while (i-->0) if (!(l==0&&i==0)) // <-------- Here it is!!!
vs = vs.slice(0,i*3+l)
+ ','
+ vs.slice(i*3+l);
$('#devCount').text(vs);
setTimeout(updateVisitors, Math.random()*2000);
};
setTimeout(updateVisitors, Math.random()*2000);
});
i-->0 is the same as i-- > 0, so the comparison expression if the evaluated value of i-- is greater than 0.
it is not an operator. See this link:
What is the "-->" operator in C++?
var i = 10;
while (i-- > 0)
{
alert('i = ' + i);
}
Output:
i = 9
i = 8
i = 7
i = 6
i = 5
i = 4
i = 3
i = 2
i = 1
i = 0
Other answers have explained that it's two operators. I'll just add that in the example, it's unnecessary. If you're counting down from a positive integer to zero, you can miss out the greater-than-zero test and your code will be shorter and, I think, clearer:
var i = 10;
while (i--) {
// Do stuff;
}
Thought of the exact same thread that JCasso thought of.
What is the "-->" operator in C++?
I think this code style stems from the early days of programming when terminals had limited display real estate.

Categories