This question already has answers here:
How to compare an array of strings in Javascript?
(6 answers)
Closed 3 months ago.
I have a little problem to solve. I want to compare two texts if they are the same.
let currentValue = "24960307.W 25880305.W 24880208.W 25650156.W"
let newValue = "24880208.W 24960307.W 25650156.W 25880305.W"
// is the same text just diferent order
// when i did includes
let x = currentValue.includes(value);
console.log(x);
//response in console
false
I tried with includes and localeCompare but still show that text is different.
A quick solution to normalize order is to split, sort, rejoin, then compare. This avoids any fancy parsing.
let currentValue = "24960307.W 25880305.W 24880208.W 25650156.W"
let newValue = "25880305.W 24880208.W 25650156.W 24960307.W"
const a = currentValue.split(' ').sort().join(' ')
const b = newValue.split(' ').sort().join(' ')
console.log(a === b)
let x = a.localeCompare(b) === 0
console.log(x);
This question already has answers here:
What exactly is Type Coercion in Javascript?
(9 answers)
Closed 2 years ago.
I have array, by which at some point am mapping the array and calculating sum and percentages. So while implementing the logic i saw that, when i use '*' directly its working but when i use '+' it just adds the two string
For example:
const a = '100';
const b = '10';
const c = a * b;
const d = a + b;
console.log(d)
When i checked the d , it gives '10010' and when c it gives '1000' ! How is this ?
But when i use parseInt(a) + parseInt(b) it works perfectly with 110 as output
In JavaScript there are no primitive datatypes like int, float etc. There are only variables which can be initialized with everything you need. For your example
const a = 100;
const b = 10;
const c = a * b;
const d = a + b;
console.log(d);
should work perfectly, because I removed ''. With '' the constant thinks it is a string provided. Without '' there are just the numbers saved in the constants. Also + doesn't work in your example, because as I said the constants think the numbers are a string due to ''. So it just puts this two "strings" together and not summing them up.
This question already has answers here:
How can I obfuscate (protect) JavaScript? [closed]
(22 answers)
Closed 3 years ago.
This question knowing that obfuscation is by no means a strong way to protect code...
Using Gulp, I'm looking for a way to prevent my app's content to appear in a too obvious manner. Not manipulating sensitive data, but I'd still not want my minified code to look too obvious to modify.
Been trying gulp-minify and gulp-uglify, but either my use of them is wrong, either they don't fill my need.
Needs being:
- function renaming
- variable renaming
- string obfuscation (at least prevent the string from being human readable at first glance)
- not more than 2x the storage needs
What would be the suggested approaches, leads, plugins?
Thanks in advance,
Just try this: Javascript Obfuscator.
As far as I know, it's almost impossible to revert the obfuscated code back to the original.
So far, the most effective (in my case) is to pipe the following code, which just applies character rotation:
function obfuscate(text, key, n = 126) {
// return String itself if the given parameters are invalid
if (!(typeof(key) === 'number' && key % 1 === 0)
|| !(typeof(key) === 'number' && key % 1 === 0)) {
return text.toString();
}
var chars = text.toString().split('');
for (var i = 0; i < chars.length; i++) {
var c = chars[i].charCodeAt(0);
if (c <= n) {
chars[i] = String.fromCharCode((chars[i].charCodeAt(0) + key) % n);
}
}
return chars.join('');
},
function defuse(text, key, n = 126) {
// return String itself if the given parameters are invalid
if (!(typeof(key) === 'number' && key % 1 === 0)
|| !(typeof(key) === 'number' && key % 1 === 0)) {
return text.toString();
}
return obfuscate(text.toString(), n - key);
}
You may want to consider gulp-javascript-obfuscator. It's a node module and version ^1.1.5 worked very well for me. It also has the option to minify with the following code:
// Imports ...
obfuscator = require('gulp-javascript-obfuscator')
// ... Other code
gulp.src('my_file.js')
.pipe(obfuscator({compact:true}))
.pipe(gulp.dest('dist'));
How can I use an inline if statement in JavaScript? Is there an inline else statement too?
Something like this:
var a = 2;
var b = 3;
if(a < b) {
// do something
}
You don't necessarily need jQuery. JavaScript alone will do this.
var a = 2;
var b = 3;
var c = ((a < b) ? 'minor' : 'major');
The c variable will be minor if the value is true, and major if the value is false.
This is known as a Conditional (ternary) Operator.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator
There is a ternary operator, like this:
var c = (a < b) ? "a is less than b" : "a is not less than b";
For writing if statement inline, the code inside of it should only be one statement:
if ( a < b ) // code to be executed without curly braces;
You can also approximate an if/else using only Logical Operators.
(a && b) || c
The above is roughly the same as saying:
a ? b : c
And of course, roughly the same as:
if ( a ) { b } else { c }
I say roughly because there is one difference with this approach, in that you have to know that the value of b will evaluate as true, otherwise you will always get c. Bascially you have to realise that the part that would appear if () { here } is now part of the condition that you place if ( here ) { }.
The above is possible due to JavaScripts behaviour of passing / returning one of the original values that formed the logical expression, which one depends on the type of operator. Certain other languages, like PHP, carry on the actual result of the operation i.e. true or false, meaning the result is always true or false; e.g:
14 && 0 /// results as 0, not false
14 || 0 /// results as 14, not true
1 && 2 && 3 && 4 /// results as 4, not true
true && '' /// results as ''
{} || '0' /// results as {}
One main benefit, compared with a normal if statement, is that the first two methods can operate on the righthand-side of an argument i.e. as part of an assignment.
d = (a && b) || c;
d = a ? b : c;
if `a == true` then `d = b` else `d = c`
The only way to achieve this with a standard if statement would be to duplicate the assigment:
if ( a ) { d = b } else { d = c }
You may ask why use just Logical Operators instead of the Ternary Operator, for simple cases you probably wouldn't, unless you wanted to make sure a and b were both true. You can also achieve more streamlined complex conditions with the Logical operators, which can get quite messy using nested ternary operations... then again if you want your code to be easily readable, neither are really that intuative.
In plain English, the syntax explained:
if(condition){
do_something_if_condition_is_met;
}
else{
do_something_else_if_condition_is_not_met;
}
Can be written as:
condition ? do_something_if_condition_is_met : do_something_else_if_condition_is_not_met;
If you just want an inline IF (without the ELSE), you can use the logical AND operator:
(a < b) && /*your code*/;
If you need an ELSE also, use the ternary operation that the other people suggested.
You could do like this in JavaScript:
a < b ? passed() : failed();
<div id="ABLAHALAHOO">8008</div>
<div id="WABOOLAWADO">1110</div>
parseInt( $( '#ABLAHALAHOO' ).text()) > parseInt( $( '#WABOOLAWADO ).text()) ? alert( 'Eat potato' ) : alert( 'You starve' );
I often need to run more code per condition, by using: ( , , ) multiple code elements can execute:
var a = 2;
var b = 3;
var c = 0;
( a < b ? ( alert('hi'), a=3, b=2, c=a*b ) : ( alert('by'), a=4, b=10, c=a/b ) );
FYI, you can compose conditional operators
var a = (truthy) ? 1 : (falsy) ? 2 : 3;
If your logic is sufficiently complex, then you might consider using an IIFE
var a = (function () {
if (truthy) return 1;
else if (falsy) return 2;
return 3;
})();
Of course, if you plan to use this logic more than once, then you aught to encapsulate it in a function to keep things nice and DRY.
inline if:
(('hypothesis') ? 'truthy conclusion' : 'falsey conclusion')
truthy conclusion: statements executed when hypothesis is true
falsey conclusion: statements executed when hypothesis is false
your example:
var c = ((a < b) ? 'a<b statements' : '!(a<b) statements');
You can use the Ternary operator which equates to a simple if, else.
Ternary operation which calls functions for both outcomes:
(a < b) ? DoSomething() : DoSomethingElse();
Ternary operation which calls a function for only one of the outcomes:
(a < b) ? DoSomething() : {}; or (a < b)?.DoSomething();
To add to this you can also use inline if condition with && and || operators.
Like this
var a = 2;
var b = 0;
var c = (a > b || b == 0)? "do something" : "do something else";
Inline if in JavaScript is simple and requires no braces:
if (a < b) doSomething()
Technically you can have an else in the same line, but it requires a semicolon:
if (a < b) doSomething(); else doSomethingElse()
The above examples may not be desired by your team's coding standards. The most important thing is that you follow conventions that work for your team. Personally, I prefer if statements over ternaries in many cases because I find them easier to read.
Isn't the question essentially: can I write the following?
if (foo)
console.log(bar)
else
console.log(foo + bar)
the answer is, yes, the above will translate.
however, be wary of doing the following
if (foo)
if (bar)
console.log(foo)
else
console.log(bar)
else
console.log(foobar)
be sure to wrap ambiguous code in braces as the above will throw an exception (and similar permutations will produce undesired behaviour.)
Simplify ternary operator
var locked = 1;
var canChange = locked != 1 ? true : false;
If the locked is 1, then the canChange variable is set to false, otherwise, it is set to true.
In this case, you can simplify it by using a Boolean expression as follows:
var locked = 1;
var canChange = locked != 1;
For multiple JavaScript ternary operators
The following example shows how to use two ternary operators in the same expression:
var speed = 90;
var message = speed >= 120 ? 'Too Fast' : (speed >= 80 ? 'Fast' : 'OK');
console.log(message);
It is a best practice to use the ternary operator when it makes the code easier to read. If the logic contains many if...else statements, you shouldn’t use the ternary operators.
(condition) ? expressionTrue : expressionFalse;
Example
int a=20, b=10;
if (a>b) {
cout << "a greater than b";
} else {
cout << "b greater than a";
}
You can simply write:
int a=20, b=10;
(a>b) ? cout << "a greater than b" : cout << "b greater than a";
I have two variables, 'a' and 'b' in my JavaScript, and i want to add them together - i assume this code:
var a = 10;
var b = 30
var varible = a + b;
This, puts the two numbers next to each other... any ideas why... the result should be 40?
You probably have strings instead of integers. That is your code really is like this:
var a = "10";
var b = "30";
var c = a + b; // "1030"
There are several ways to convert the strings to integers:
a = parseInt(a, 10); // Parse the string
b = b * 1; // Force interpretation as number
new is a reserved word, I'd use something else in any case.
And with a normal variable name of c it worked for me:
var a = 10;
var b = 30
var c = a + b;
alert(c);
did the expected and alerted 40
new is a keyword in JavaScript. you should not use it to declare your variables or functions. change the variable name from new to something else
Are you sure you didn't do this:
var a = '30';
var b = '40';
Here, I show '30' as a string rather than a number, and I would expect the "+" operator to concatenate two strings. Since this is contrived code, you may not be entirely sure where your variables were initially assign or what type they have. You can check it like this:
var a = '30';
var b = '40';
alert( typeof(a) + '\n' + typeof(b) );
If either of those say 'object' or 'string' rather than 'number' this is your problem. One way this might happen that you didn't expect is with an input. Say you have code like this:
<input id="a" value="30" />
<input id="b" value="40" />
<script language="javascript">
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
</script>
Here, the value of a text input is always a string initially.
If you want to convert a variable to a number first you should use something like myVar - 0 to coerce a numeric operation or the more-formal parseInt() or parseFloat() functions (don't forget the radix parameter for parseInt()). And always check isNaN() on the results.
I'm really surprised that noone has until now suggested the obvious: "Casting" with JavaScript (I set it in quotes, because it is no real casting).
var a = "1"; // string
var b = Number(a); // number
var c = String (b); // string again
a + b; // "11"
b + a; // 2
a + c; // "11"
Now, why is this no real casting? Because you don't create a new variable of type "number" but a new object "Number" and initialize it with something that could be numerical.
One or both is a string. If you get the values from a HTML input or something, they definitely are. Make sure they're both integers by using parseInt:
var newValue = parseInt(a,10) + parseInt(b,10);
Also, 'new' is a keyword. You can't use that for a variable name :)