I just started using Javascript and I have a small beginner question.
I have created 2 functions, only when I place an argument for a function my 2 parameters are seen as a string and they are not added properly.
par1 = 5 , par2 = 2
function sum(par1,par2){
return document.write("Sum : " + par1+par2 + "<br>");
}
function multi(par1,par2){
return document.write(" Multi : "+par1*par2);
}
If I remove the "Sum:" + function from the sum function, it adds up well, but if I leave it in, my parameters are seen as string and I get result 52 instead of 7.
In multi function it just works well.
Thank you in advance for answering my question!
The reason is that when you write:
"some string"+5
javascript interprets the + operator as concatenate, because that's the only thing that's meaningful for a string, and it assumes that you are concatenating two strings.
Since ES6 javascript has string interpolation, you could write:
document.write(`Sum: ${par1 + par2} <br>`)
Just wrap it with ().. example below
<!DOCTYPE html>
<head>
</head>
<body>
</body>
<script type="text/javascript">
function sum(par1,par2){
//Wrap "par1" and "par2" with ()
return document.write("Sum : " + (par1+par2) + "<br>");
}
function multi(par1,par2){
//Wrap "par1" and "par2" with ()
return document.write(" Multi : "+ (par1*par2));
}
sum(5,2);
multi(5,2);
</script>
</html>
Hope this helps
From my experience it does that because you are adding a string to an integer. If you do something like:
return ("Sum:", (par1 + par2))
That should work.
In JavaScript the '+' with a string just concatenates. For example:
const a = 1 + 1 // returns 2
const b = "2" + 2 // returns 22
const c = 3 + 3 + "3" + 3 // 633
const d = "Hello" + "World" + 4 // returns HelloWorld4
Related
I'm getting undefined instead of a String on return of the answer - though it is the right correct characters being logged. How do I get it to output a definite string?
var greet = function(name) {
let first = String(name. charAt(0). toUpperCase());
let second = String(name.slice(1));
console.log('Hello ' + first + second + '!');
}
You forgot to return a value, so the return-value is undefined.
var greet = function(name) {
let first = String(name. charAt(0). toUpperCase());
let second = String(name.slice(1));
return 'Hello ' + first + second + '!';
}
console.log(greet('Gemma'));
The console will print the result of evaluating an expression. You can notice if you set
let name = 'john'
it will print undefined in the very next line.
That is also happening here. First it is printing your value, then it print undefined.
Your function is working fine - you just need to invoke it and feed its argument with a name...
[for the result look in the console]
var greet = function(name) {
let first = String(name.charAt(0).toUpperCase());
let second = String(name.slice(1));
console.log('Hello ' + first + second + '!');
}
;
greet("henky");
Line break in javascipt string console
console.log("Foo" + "\n" + "Bar");
Line break in javascript object console
console.log({ value : "Foo\nBar" });
Is it possible to add linebreaks in javascript objects.
The answer is no: when you print an object to the console log, strings will be written as javascript objects (similar but not identical to what you'd get if you explicitly converted them into JSON, like console.log(JSON.stringify(object))).
If you want for some reason to print your strings with line breaks, you'd have to implement the object-to-string conversion yourself; perhaps with something like this:
function customString(object) {
let string = '{\n';
Object.keys(object).forEach(key => {
string += ' "' + key + '": "' + object[key] + '"\n';
});
string += '}';
return string;
}
console.log(customString({ value: "Foo\nBar" }));
(It sounds like you have an idea in mind of exactly how you want this output to look, so adjust the function above until it works as expected.)
You can make JSON pretty with automatic line breaks using:
console.log(JSON.stringify({ test: { key: { inner: 'val' } }}, null , 2))
Where 2 is the number of spaces/indent for each level.
You can use ES6:
console.log(`hello
world`)
will produce:
hello
world
I think its originally creating a line break, but due to the object, it's not showing directly. Try to assign it in variable and access that in the console.
Code:
var v = {val:"test\ntest"};
console.log(v.val);
Output:
test
test
I have a function that returns long numbers. 23.23423423423432
I can strip the decimal places:
function shortNumbers(){
var longNumber = 34.324234234234;
var shortNumber = longNumber.toPrecision(2)
alert("Shorter number is " + shortNumber)
}
Next I want to use map to display the values in an alert:
function collectVideoValues(){
var loopsStr = loops.map(x=>x.start+"AA"+x.end).join('AA');
alert("Video Values are " + videoId + "," +loopsStr );
}
Can I insert toPrecision after loops.map ?
loops.map.toPrecision(2).(x=>x.start+"AA"+x.end).join('AA');
I'd like to solve this in 1 or 2 lines of code without making a second function.
I placed toPrecision after x.start and x.end to strip the decimal places from the number.
function collectVideoValues(){
var loopsStr = loops.map(x=>x.start.toPrecision(2)+"i"+x.end.toPrecision(2)).join('i');
document.getElementById("lesson-code").innerHTML= videoId + "ID"+ loopsStr;
}
I'm doing some JavaScript koans to learn syntax and I came across one case where I'm a bit confused. This is the code:
it("should know properties that are functions act like methods", function () {
var megalomaniac = {
mastermind : "Brain",
henchman: "Pinky",
battleCry: function (noOfBrains) {
return "They are " + this.henchman + " and the" +
Array(noOfBrains + 1).join(" " + this.mastermind);
}
};
var battleCry = megalomaniac.battleCry(4);
expect("They are Pinky and the Brain Brain Brain Brain").toMatch(battleCry);
});
Because the battleCry function creates an array with noOfBrains + 1 elements, and noOfBrains is passed in as 4 I would have expected the join() to print 5 "Brain" not 4. Why is it 4?
Thanks!
You get an array of size 5 (= 4 + 1). You then join these together.
Note that the Brain (the glue) is only applied to the joined parts. As your array is size 5, you need 4 "glue parts" to create a String.
Hence the 4 Brain.
If one did something as
Array(noOfBrains + 1).map(e => 'Brain').join(' ')
you would indeed get 5 items
how can I split a number into sub digits. I have a number 20:55 n need to split in to two parts as 20 and 55.
var mynumber = 20:55;
var split = mynumber.toString();
document.write("Hour : " + split[0]);
document.write("Minutes : " + split[1]);
but am getting wrong value after toString() function call.
EDIT: 1 This is what I want. This is working fine but only works with windows. In linux Firefox am not getting the correct value in function .. something like 12.200000000000000001 instead of 12.25
<script type="text/javascript">
var myarray = new Array();
myarray = [[12.25, 1],[13.25,1]];
//alert(myarray[0][0]);
func(myarray[0][0]) ;
function func(n) {
var split = n.split(".");
document.writeln("Number : " + n); // Number : 12.25
document.writeln("Hour : " + split[0]); // Hour : 12
document.writeln("Minutes : " + split[1]); // Minutes : 25
}
</script>
Use split() function
var number_array=mynumber.split(":")
On your example
var mynumber = "20:55";
var split = mynumber.split(":");
document.write("Hour : " + split[0]);
document.write("Minutes : " + split[1]);
More on this
http://www.w3schools.com/jsref/jsref_split.asp
You are using split(), a string function, on a number. Use this:
var split = n.toString().split(".");
Works perfectly on Firefox 3.6.3 (and Opera 10.60, and Chromium 5), Ubuntu Linux 10.04.
Use split function
var numSplit = mynumber.split(':');
Then you can access each value using numSplit[0] and numSplit[1]