I've started to go through Node tutorials on nodeschool.io, and the second assignment was to write a program that will count the number of newlines in a file and print it out. My solution looks like this
var fs = require('fs'); var file = process.argv; var buff = fs.readFileSync(file); var str = buff.toString(); var str_arr = str.split('\n'); var newline_length = str_arr.length-1; console.log(newline_length);
It's correct, and works. Theirs is
var fs = require('fs') var contents = fs.readFileSync(process.argv) var lines = contents.toString().split('\n').length - 1 console.log(lines) // note you can avoid the .toString() by passing 'utf8' as the // second argument to readFileSync, then you'll get a String! // // fs.readFileSync(process.argv, 'utf8').split('\n').length - 1
While both are correct, mine is longer (more lines used because I declared variables at every step).
I am wondering, am I wrong in declaring the variables for every step and then working on the code as I go? I mean, it does take more space, but I have the feeling that it's a bit clearer what I'm doing, unlike theirs. Or am I mistaken and haven't really gotten to that level where I can safely write everything in a one line like they did?
Also am I using memory space by declaring too many variables?